LeetCode ยท #7
Reverse Integer Solution
Reverse the digits of a 32-bit signed integer. Return 0 if the result overflows.
01
Section One ยท Problem
Problem Statement
Example
Input: x = 123 Output: 321 Input: x = -123 Output: -321 Input: x = 120 Output: 21
Constraints
โข -2ยณยน โค x โค 2ยณยน - 1 โข Cannot store 64-bit integers (check overflow before it happens)
02
Section Two ยท Approach 1
String Reversal
Convert to string, reverse, parse. Must handle sign and leading zeros. Overflow check after parsing.
Better: Mathematical pop & push with overflow check before multiplication. No string needed.
03
Section Three ยท Approach 2
Pop & Push with Overflow Check โ O(logโโ n)
Pop last digit: digit = x % 10; x /= 10. Push to result: result = result * 10 + digit. Before pushing, check if result * 10 + digit would overflow.
๐ก Mental model: Read the number from right to left (pop with mod 10), and write it from left to right (push with ร10 + digit). Before each write, check: "will adding this digit overflow my 32-bit paper?"
Overflow check
- If
result > INT_MAX/10or(result == INT_MAX/10 && digit > 7)โ overflow. - If
result < INT_MIN/10or(result == INT_MIN/10 && digit < -8)โ underflow.
๐ฏ Pattern: "Reverse digits of an integer with 32-bit constraint." The key is the pre-multiplication overflow check. Applied similarly in LC 8 (String to Integer) and LC 9 (Palindrome Number).
04
Section Four ยท Trace
Visual Walkthrough
Reverse Integer โ Pop & Push
05
Section Five ยท Implementation
Code โ Java & Python
Java
class Solution {
public int reverse(int x) {
int res = 0;
while (x != 0) {
int digit = x % 10;
x /= 10;
if (res > Integer.MAX_VALUE / 10
|| (res == Integer.MAX_VALUE / 10 && digit > 7)) return 0;
if (res < Integer.MIN_VALUE / 10
|| (res == Integer.MIN_VALUE / 10 && digit < -8)) return 0;
res = res * 10 + digit;
}
return res;
}
}
Python (no overflow in Python, but check range)
class Solution:
def reverse(self, x: int) -> int:
sign = -1 if x < 0 else 1
rev = int(str(abs(x))[::-1]) * sign
return rev if -2**31 <= rev <= 2**31 - 1 else 0
06
Section Six ยท Analysis
Complexity Analysis
| Approach | Time | Space |
|---|---|---|
| Pop & push | O(logโโ n) | O(1) |
07
Section Seven ยท Edge Cases
Edge Cases & Pitfalls
| Case | Input | Why It Matters |
|---|---|---|
| Overflow | 1534236469 | Reversed = 9646324351 > INT_MAX โ return 0. |
| Trailing zeros | 120 | Reversed = 21 (leading zeros drop). |
| Negative | -123 | Pop gives negative digits. Works naturally with %. |
| Zero | 0 | Return 0. |
โ Common Mistake: Checking overflow AFTER
result = result * 10 + digit. By then it's already overflowed (undefined behavior in C/C++, wraps in Java). Check BEFORE the multiplication. Compare result against INT_MAX / 10.