Reverse Integer: Digit Extraction with Overflow Check
Reverse Integer is LeetCode 7. Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2**31, 2**31 - 1], return 0.
A few examples:
123becomes321-123becomes-321120becomes21
The problem is not about string manipulation. The intended approach uses pure math: extract digits one at a time using modulo and integer division, and build the reversed number as you go.
The approach
The algorithm has one loop that runs until x reaches zero. Each iteration does three things:
- Extract the last digit using
x % 10. - Append that digit to the reversed number:
rev = rev * 10 + digit. - Remove the last digit from
xusing integer division:x = x // 10.
Before appending the digit, you must check whether rev * 10 + digit would overflow the 32-bit signed range. If it would, return 0 immediately.
That is the entire algorithm. No string conversion, no array of digits, no extra space.
The mod operator % in Python returns a result with the same sign as the divisor, not the dividend. For negative numbers, this means x % 10 can give unexpected results. The cleanest approach is to work with the absolute value of x and restore the sign at the end.
Python solution
def reverse(x):
INT_MAX = 2**31 - 1
INT_MIN = -(2**31)
sign = -1 if x < 0 else 1
x = abs(x)
rev = 0
while x != 0:
digit = x % 10
if rev > (INT_MAX - digit) // 10:
return 0
rev = rev * 10 + digit
x //= 10
return sign * rev
Visual walkthrough
Here is the mod/divide loop traced step by step on the input 123. Each step extracts one digit and shifts it into the reversed result.
reverse(123):Step 1: Extract the last digit of 123.
123 % 10 = 30 * 10 + 3 = 312digit = 123 % 10 = 3. Build rev = 0 * 10 + 3 = 3. Then x becomes 123 // 10 = 12.
Step 2: Extract the last digit of 12.
12 % 10 = 23 * 10 + 2 = 321digit = 12 % 10 = 2. Build rev = 3 * 10 + 2 = 32. Then x becomes 12 // 10 = 1.
Step 3: Extract the last digit of 1.
1 % 10 = 132 * 10 + 1 = 3210digit = 1 % 10 = 1. Build rev = 32 * 10 + 1 = 321. Then x becomes 1 // 10 = 0. Loop ends.
321 is within [-2^31, 2^31 - 1], so no overflow. Return 321.
The key insight is that % 10 always gives you the rightmost digit, and // 10 removes it. The reversed number is built left-to-right by multiplying the accumulator by 10 and adding the new digit.
Overflow handling
The overflow check is where most mistakes happen. You need to detect that rev * 10 + digit would exceed 2**31 - 1 (which is 2147483647) before you actually compute it.
The check is:
if rev > (INT_MAX - digit) // 10:
return 0
Why this works: you want to know if rev * 10 + digit > INT_MAX. Rearranging gives rev > (INT_MAX - digit) / 10. Using integer division on the right side keeps everything safe from overflow.
For example, if rev = 214748365 and digit = 0, then (2147483647 - 0) // 10 = 214748364. Since 214748365 > 214748364, you know the result would overflow, so you return 0.
In Python, integers have arbitrary precision, so you will not get a runtime overflow. But the problem requires you to return 0 for any result outside [-2**31, 2**31 - 1]. If you skip the pre-check and just compare at the end, it still works in Python, but it shows the interviewer you do not understand the pattern. In C++ or Java, skipping the pre-check is an actual bug.
Complexity analysis
| Metric | Value | Why |
|---|---|---|
| Time | O(log n) | The number of digits in n is floor(log10(n)) + 1. Each iteration removes one digit. |
| Space | O(1) | Only a few integer variables. No arrays, no strings. |
The loop runs exactly once per digit, and the number of digits in n is proportional to log10(n). This is optimal since you need to look at every digit at least once.
Building blocks
Reverse Integer is built from one fundamental brick that appears in many math and number manipulation problems.
Digit extraction with mod/divide
The % 10 / // 10 loop is the standard way to process individual digits of an integer without converting to a string. You extract the last digit with modulo, do something with it, then chop it off with integer division.
This same loop appears in:
- Palindrome Number (LeetCode 9) uses the same digit extraction to build the reversed number and compare it to the original.
- Add Digits (LeetCode 258) sums digits using
% 10and// 10repeatedly. - String to Integer (atoi) (LeetCode 8) builds a number digit by digit and uses the same overflow check.
Pre-multiplication overflow check
The technique of checking rev > (INT_MAX - digit) // 10 before multiplying is the exact same pattern used in atoi and any problem where you accumulate a number digit by digit.
If you can write the mod/divide digit extraction loop from scratch, you unlock Reverse Integer, Palindrome Number, and the digit-summing family of problems. Pair it with the overflow check and you also have the core of atoi. These two bricks are small enough to drill in under five minutes each.
Edge cases
Negative numbers. The sign does not affect the reversal logic. Strip the sign, reverse the absolute value, and reattach the sign at the end. -123 becomes -321.
Trailing zeros. 120 reversed is 21, not 021. This happens automatically because 0 * 10 + ... at the start of rev does not preserve leading zeros.
Overflow after reversal. 1534236469 reversed is 9646324351, which exceeds 2**31 - 1. The overflow check catches this mid-loop and returns 0.
Single digit. Any single-digit integer reversed is itself. The loop runs once, extracts that digit, and returns it.
Zero. x = 0 means the while loop body never executes. rev stays 0, which is correct.
Minimum 32-bit value. x = -2147483648 reversed is -8463847412, which overflows. Return 0.
From understanding to recall
You can understand this solution in a few minutes. The mod/divide loop makes sense once you see it. The overflow check is a one-liner. But understanding is not the same as being able to write it from scratch during an interview.
The digit extraction loop (% 10 to get the digit, // 10 to remove it, multiply-and-add to build the result) is a tiny building block. It takes under two minutes to type out. The overflow check is one line. If you drill these two pieces a few times with spaced repetition, they will stick. And when you see Palindrome Number, atoi, or any other digit-by-digit problem, you are not starting from scratch. You are assembling bricks you already own.
Related posts
- Palindrome Linked List - Another palindrome problem where reversing half the structure is the key technique
- String to Integer (atoi) - Uses the same overflow check and digit-by-digit accumulation pattern