Pop and push digits
Time O(log x) Space O(1)d = x % 10; x /= 10; check bounds; r = r × 10 + d. Java's % keeps the sign, so negatives work unchanged.
x = -123vars(vars)
Step 1/4In Java, -123 % 10 is -3, so the digits come out negative and the sign takes care of itself.
class Solution {
public int reverse(int x) {
int r = 0;
while (x != 0) {
int d = x % 10;
x /= 10;
if (r > Integer.MAX_VALUE / 10 || (r == Integer.MAX_VALUE / 10 && d > 7)) return 0;
if (r < Integer.MIN_VALUE / 10 || (r == Integer.MIN_VALUE / 10 && d < -8)) return 0;
r = r * 10 + d;
}
return r;
}
}Verdict: Overflow check without long.