Problem
Given a 32-bit signed integer, reverse its digits. Return 0 if the result overflows 32-bit range.
Example
Input: 123
Output: 321
Input: -123
Output: -321
Input: 1534236469
Output: 0
Overflow.
Solution
Pop digits with mod 10, push to result by multiplying by 10. Check for overflow.
def reverse(x):
sign = -1 if x < 0 else 1
x = abs(x)
result = 0
while x:
result = result * 10 + x % 10
x //= 10
result *= sign
return 0 if result < -2**31 or result > 2**31 - 1 else result
function reverse(x) {
const sign = x < 0 ? -1 : 1;
x = Math.abs(x);
let result = 0;
while (x) {
result = result * 10 + (x % 10);
x = Math.floor(x / 10);
}
result *= sign;
return (result < -(2**31) || result > 2**31 - 1) ? 0 : result;
}
int reverse(int x) {
long result = 0;
while (x) {
result = result * 10 + x % 10;
x /= 10;
}
return (result < INT_MIN || result > INT_MAX) ? 0 : (int)result;
}
public int reverse(int x) {
long result = 0;
while (x != 0) {
result = result * 10 + x % 10;
x /= 10;
}
return (result < Integer.MIN_VALUE || result > Integer.MAX_VALUE) ? 0 : (int) result;
}
Complexity
- Time: O(log x)
- Space: O(1)
Explanation
In C++/Java use long to detect overflow. In Python integers are unbounded but you must manually check the 32-bit range.
Comments
Join the discussion. Got a question, found an issue, or want to share your experience?