7. Reverse Integer


Remembering the formula:
res = res*10 + x%10 (remainder)
x /=10
notice the boundary
time: O(n)
space: O(1)
class Solution {
public int reverse(int x) {
long res = 0;
while (x != 0) {
res = res*10 + x%10;
x /= 10;
if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) return 0;
}
return (int)res;
}
}
Last updated
Was this helpful?