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

๐Ÿท๏ธ

Difficulty

Medium

๐Ÿ”—

LeetCode

Problem #7

๐Ÿ—๏ธ

Pattern

Math โ€” digit manipulation

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/10 or (result == INT_MAX/10 && digit > 7) โ†’ overflow.
  • If result < INT_MIN/10 or (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
x=123. Pop digits: 3, 2, 1. Push: 0โ†’3โ†’32โ†’321. digit=3, result=0*10+3=3, x=12. digit=2, result=3*10+2=32, x=1. digit=1, result=32*10+1=321, x=0. return 321 โœ“
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

ApproachTimeSpace
Pop & pushO(logโ‚โ‚€ n)O(1)
07
Section Seven ยท Edge Cases

Edge Cases & Pitfalls

CaseInputWhy It Matters
Overflow1534236469Reversed = 9646324351 > INT_MAX โ†’ return 0.
Trailing zeros120Reversed = 21 (leading zeros drop).
Negative-123Pop gives negative digits. Works naturally with %.
Zero0Return 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.

โ† Back to Math & Bit problems