Reverse Integer looks trivial — flip the digits of a number — but it is a classic interview filter. The real test is handling the sign and the 32-bit overflow check without ever turning the number into a string.
Problem. Given a signed 32-bit integer x, return x with its digits reversed. If reversing
causes the value to fall outside the 32-bit range [-2^31, 2^31 - 1], return 0 instead.
Example: x = 123 → 321. And x = -123 → -321. And x = 120 → 21 (trailing zeros vanish).
The slow way first
The tempting shortcut is to convert the number to a string, reverse the characters, and parse it back. That works in a scratch script, but interviewers usually ban it: it dodges the arithmetic the question is really about, and it makes the overflow check awkward. The expected solution uses only integer math.
The question to ask: how do I peel a number apart one digit at a time? The last digit of any number is what is left over when you divide by ten — that is x % 10. Drop it with integer division by ten, and repeat.
The idea: pop a digit, push a digit
Keep a running result rev that starts at 0. While x still has digits:
- Pop the last digit of
x:digit = x % 10, then shrinkxwithx = x // 10. - Push that digit onto
rev:rev = rev * 10 + digit. Multiplyingrevby ten shifts every existing digit one place left, opening a slot for the new one.
Handle the sign separately (work on the absolute value, reapply the sign at the end), and before returning, confirm rev still fits in 32 bits.
The key insight: rev * 10 + digit builds the answer from the most significant digit down, because the first digit we pop off x (its last one) becomes the first digit we place into rev (its highest one).
Walk through it
Step through the animation with x = 123. The top row is what remains of x; the bottom row is rev filling up. We pop 3, then 2, then 1, and each lands one place further left in rev: 3, then 32, then 321. When x hits 0, the loop ends and we return 321.
Pseudocode
sign = +1 if x >= 0 else -1
x = absolute value of x
rev = 0
while x is not 0:
digit = x % 10 # pop the last digit
x = x // 10 # remove it from x
rev = rev * 10 + digit # push it onto rev
rev = rev * sign
if rev is outside [-2^31, 2^31 - 1]:
return 0
return revThe Python solution
def reverse(x):
sign = 1 if x >= 0 else -1
x, rev = abs(x), 0
while x != 0:
digit = x % 10
x = x // 10
rev = rev * 10 + digit
rev *= sign
return rev if -2**31 <= rev <= 2**31 - 1 else 0signis saved up front so we can work onabs(x)and avoid Python's floor-division surprises with negatives.digit = x % 10pops the last digit;x = x // 10removes it so the next turn sees a shorter number.rev = rev * 10 + digitis the push: the* 10shifts existing digits left, and+ digitdrops the new one into the ones place.- The loop ends naturally when
xreaches0— no length counting needed. - The final line reapplies the sign and clamps to the 32-bit range, returning
0on overflow.
Complexity
| Case | Time | Notes |
|---|---|---|
| String reverse | O(d) (moderate) | but dodges the real arithmetic |
| Digit math (this solution) | O(d) (moderate) | d = number of digits, about log10(x) |
O(1) (fast)There are only as many loop turns as there are digits, which is O(log x). We use a constant amount of extra memory — just rev, digit, and sign — so the space is O(1).
When this pattern shows up
The pop-and-push digit loop — x % 10 to read the last digit, x // 10 to drop it, rev * 10 + digit
to build a new number — is the backbone of many number problems: palindrome number, add digits, sum of
digits, and integer-to-Roman style conversions. Memorize the two lines.
Do the overflow check on the result, not mid-loop guesswork, and remember the asymmetric bound: the
negative limit -2^31 has a larger magnitude than the positive limit 2^31 - 1. Forgetting the 32-bit
clamp is the single most common reason this problem is failed.
Practice
For x = 120, what does rev hold after each pop, and what is the final answer?
1. What does x % 10 give you?
2. Why multiply rev by 10 before adding the new digit?
3. When does the while loop stop?
4. What should the function return if the reversed value exceeds 2^31 - 1?