Reverse Integer
Problem
Given a 32-bit signed integer x, reverse its digits. If reversing causes the value to overflow signed 32-bit range, return 0.
x = 123321def reverse(x):
sign = -1 if x < 0 else 1
x = abs(x)
res = 0
while x:
res = res * 10 + x % 10
x //= 10
res *= sign
if res < -2**31 or res > 2**31 - 1:
return 0
return res
function reverse(x) {
const sign = x < 0 ? -1 : 1;
x = Math.abs(x);
let res = 0;
while (x) {
res = res * 10 + x % 10;
x = Math.floor(x / 10);
}
res *= sign;
if (res < -(2 ** 31) || res > (2 ** 31) - 1) return 0;
return res;
}
class Solution {
public int reverse(int x) {
long res = 0;
int sign = x < 0 ? -1 : 1;
x = Math.abs(x);
while (x != 0) {
res = res * 10 + x % 10;
x /= 10;
}
res *= sign;
if (res < Integer.MIN_VALUE || res > Integer.MAX_VALUE) return 0;
return (int) res;
}
}
int reverse(int x) {
long long res = 0;
int sign = x < 0 ? -1 : 1;
long long y = llabs((long long)x);
while (y) {
res = res * 10 + y % 10;
y /= 10;
}
res *= sign;
if (res < INT_MIN || res > INT_MAX) return 0;
return (int) res;
}
Explanation
To reverse a number's digits we don't need strings at all — we can peel digits off the back and stack them onto a result, one at a time.
First we remember the sign and work with abs(x) so we only deal with positive math. Then we repeat: x % 10 grabs the last digit, and res = res * 10 + digit pushes it onto the growing result. x //= 10 drops that last digit so we move to the next one.
When x hits 0 we have all the digits reversed. We multiply back the sign, then check the 32-bit range: if the answer is below -2^31 or above 2^31 - 1, we return 0 because it overflowed.
Example: x = 123. Peel 3 → res = 3; peel 2 → res = 32; peel 1 → res = 321. Sign is positive and 321 fits, so the answer is 321.
The key idea is that multiplying the running result by 10 makes room for the next digit, so the digits naturally come out in reverse order.