Reverse Integer
Medium Overflow checks
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Reverse the digits of a 32-bit signed integer. If the reversed value doesn't fit in 32 bits, return 0. You may not use 64-bit integers.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: reverse the digits but return 0 if the answer doesn't fit in an int, and you can't use long to cheat.
Why this works: before adding a digit, compare the current result with MAX/10. If it's already bigger, the next step would overflow.
Example: x = -123
d = -3 → rev = -3d = -2 → rev = -32d = -1 → rev = -321
✦Hints open one at a time
↗Approach
Pop the last digit and push it onto rev. Before each push, compare rev with MAX_VALUE / 10 (and MIN_VALUE / 10). If it's already beyond, the next step overflows, so return 0.
</>Solution (Java)
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int d = x % 10;
x /= 10;
if (rev > Integer.MAX_VALUE / 10 || (rev == Integer.MAX_VALUE / 10 && d > 7)) return 0;
if (rev < Integer.MIN_VALUE / 10 || (rev == Integer.MIN_VALUE / 10 && d < -8)) return 0;
rev = rev * 10 + d;
}
return rev;
}
}
!Common mistake
Checking for overflow after the multiplication — by then the value has already wrapped around.
- Time: O(log10 x).
- Space: O(1).
