7. Reverse Integer
Last updated
Last updated
/**
* Time complexity : O(log(x)). There are roughly log10(x) digits in x.
* Space complexity : O(1)
*/
class Solution {
public int reverse(int x) {
int n = 0, flag = (x < 0)? -1: 1;
x *= flag;
while(x > 0) {
int pop = x%10;
if(n > Integer.MAX_VALUE/10 ||
(n == Integer.MAX_VALUE/10 && pop > 2)) return 0;
n = (n*10) + pop;
x /= 10;
}
return n * flag;
}
}