Intuition
Peel the last digit off x with % 10 and append it to the result with * 10. Before each append, check whether the multiply would overflow the 32-bit range and bail out with 0 if so.
Explanation
Walk-through
Let INT_MAX = 2^31 - 1 = 2147483647 and INT_MIN = -2^31 = -2147483648.
- Keep a running
result = 0. Preserve the sign; work on the digits. - While
x != 0:digit = x % 10(the current last digit).x = x // 10(drop that digit).- Overflow guard (before
result = result * 10 + digit): ifresult > INT_MAX // 10, orresult == INT_MAX // 10anddigit > 7, the positive value would overflow → return0. Symmetric check againstINT_MINfor negatives. result = result * 10 + digit.
- Return
result.
Worked example
x = 123:
- digit
3→ result0*10 + 3 = 3, x = 12 - digit
2→ result3*10 + 2 = 32, x = 1 - digit
1→ result32*10 + 1 = 321, x = 0 - Return
321.
Why the guard matters
The problem forbids 64-bit storage, so you cannot reverse first and check afterward — the intermediate result * 10 + digit would already have overflowed. Checking against INT_MAX // 10 before multiplying keeps every value in range.
Complexity
- Time: O(log₁₀ x) — one step per digit.
- Space: O(1).
Implementation
class Solution {
public int reverse(int x) {
int result = 0;
while (x != 0) {
int digit = x % 10;
x /= 10;
// Guard against 32-bit overflow before multiplying.
if (result > Integer.MAX_VALUE / 10 ||
(result == Integer.MAX_VALUE / 10 && digit > 7)) {
return 0;
}
if (result < Integer.MIN_VALUE / 10 ||
(result == Integer.MIN_VALUE / 10 && digit < -8)) {
return 0;
}
result = result * 10 + digit;
}
return result;
}
}