Skip to content

Instantly share code, notes, and snippets.

@yitonghe00
Created February 11, 2020 09:26
Show Gist options
  • Save yitonghe00/c96518755394c5b8af59093204666200 to your computer and use it in GitHub Desktop.
Save yitonghe00/c96518755394c5b8af59093204666200 to your computer and use it in GitHub Desktop.
7. Reverse Integer (https://leetcode.com/problems/reverse-integer/): Given a 32-bit signed integer, reverse digits of an integer.
// Math solution: Pull the digits and take care of the overflow
// Time: O(logx), 1ms
// Space: O(1), 36.6mb
class Solution {
public int reverse(int x) {
int ans = 0;
while(x != 0) {
int tail = x % 10;
int newAns = ans * 10 + tail;
// !!: Take care the overflow by checking if result is as we expected when adding newAns
if((newAns - tail) / 10 != ans) return 0;
ans = newAns;
x /= 10;
}
return ans;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment