Reverse Integer
Table of Contents + β
Reverse Integer sounds like a beginner question. Just flip the digits. But the real test is hidden. The reversed number might be too big to fit in a 32-bit box. The interviewer wants to see if you catch that overflow before it happens. That is the whole point.
π― The Problem
You get a signed whole number. You reverse its digits and return the result. The tricky part is the overflow check at the end.
The rules:
- Reverse the order of the digits.
- The sign stays the same.
- If the reversed number does not fit inside a signed 32-bit integer, return
0.
Let us try 123. Reversing the digits gives 321. The sign was positive, so it stays positive.
Input: x = 123Output: 321
Explanation: the digits 1 2 3 become 3 2 1A signed 32-bit integer holds values from about minus two billion to plus two billion. If the flipped number goes past that range, we must return 0. That edge is the trap. A number like 1534236469 reverses into something too large, so the answer there is 0.
Here is the digit flip for 123. We pull digits off the back and stack them onto the answer.
π’ Approach 1: Reverse a String (Brute Force)
The idea in one line: turn the number into text, reverse the text, turn it back.
The idea:
- Drop the minus sign.
- Reverse the characters.
- Turn the reversed text back into a number.
- Put the sign back, then check it fits in 32 bits.
Why it is weak:
- It leans on string conversion.
- Some interviewers want a pure number solution.
- You still must do the overflow check at the end.
- So the string route does not save you from the hard part.
Here is the string-reversal code:
def reverse(x): sign = -1 if x < 0 else 1 reversed_value = sign * int(str(abs(x))[::-1]) if reversed_value < -(2 ** 31) or reversed_value > 2 ** 31 - 1: return 0 return reversed_valueβ‘ Approach 2: Pull Digits With Modulo (Best)
The idea in one line: peel digits off the back with arithmetic and stack them onto the answer.
The idea:
- Modulo is the remainder after division.
x % 10gives the last digit.x / 10removes that last digit.
How it works:
- Build the answer with
rev = rev * 10 + digit. - Multiplying by ten shifts everything left one place.
- Then drop the new digit into the empty ones place.
How to guard overflow:
- Check before each multiply, never after.
- Compare
revagainst the 32-bit limit divided by ten. - If
revis already bigger, stop and return0. - Once
rev * 10overflows, the value is garbage and useless to test.
Why it is fast:
- It uses only arithmetic and a couple of variables.
- No string, so the extra memory is tiny.
Here is the decision flow with the overflow guard built in.
Steps to Solve
- Remember the sign, then work with the absolute value if your language needs it.
- Start the reversed number at zero.
- Pull the last digit with
x % 10. - Before multiplying, check if
rev * 10 + digitwould pass the 32-bit limit. If yes, return0. - Update
rev = rev * 10 + digit. - Remove the last digit with integer division by ten.
- Repeat until
xis zero, then return the signed result.
This Python version reverses the digits and checks the 32-bit range by hand, since Python integers never overflow on their own.
def reverse(x): INT_MAX = 2**31 - 1 # largest signed 32-bit value INT_MIN = -2**31 # smallest signed 32-bit value sign = -1 if x < 0 else 1 x = abs(x) rev = 0 while x != 0: digit = x % 10 # last digit rev = rev * 10 + digit # build the reversed number x //= 10 # drop the last digit rev *= sign # put the sign back if rev < INT_MIN or rev > INT_MAX: # overflow guard return 0 return rev
print(reverse(123))The output of the above code will be:
321Let us walk through the Python version line by line.
INT_MAX = 2**31 - 1INT_MIN = -2**31These two lines spell out the signed 32-bit range. The biggest value is two to the power thirty-one, minus one. The smallest is the negative of two to the power thirty-one. We compare against these at the end. Python numbers grow without limit, so we must check the range ourselves.
sign = -1 if x < 0 else 1x = abs(x)We record the sign first. Then we work with the absolute value, which is the number without its sign. This keeps the digit pulling simple, because we never worry about a negative remainder.
while x != 0: digit = x % 10 rev = rev * 10 + digit x //= 10This is the core loop. x % 10 pulls the last digit. rev * 10 + digit shifts the current answer left one place and drops the new digit into the ones place. x //= 10 removes the digit we just used. The loop ends when every digit has moved over.
rev *= signThe digits are reversed using the positive value. So now we put the original sign back on the result.
if rev < INT_MIN or rev > INT_MAX: return 0return revFinally we check the 32-bit range. If the reversed number escaped the range, we return 0 as the rules demand. Otherwise we return the reversed number.
β±οΈ Time and Space Complexity
The number has a fixed handful of digits, so the loop runs a small constant number of times. We call that O(1) time for practical purposes, or O(d) where d is the digit count. We use only a couple of variables, so the space is O(1). The string approach has the same complexity but adds the cost of building a string.
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| String reverse | O(d) | O(d) |
| Modulo and divide | O(d) | O(1) |
Tip
The overflow check must come before the multiply, not after. Once rev * 10 has already overflowed, the value is garbage and your test is useless. So compare rev against the limit divided by ten first, then multiply.
π§© Key Takeaways
- β
Pull digits off the back with
x % 10, then drop them with integer division. - β
Build the answer with
rev = rev * 10 + digit, which shifts then adds. - β
The reversed number can be too big for a signed 32-bit box, so return
0then. - β Check for overflow before the multiply, never after it.
- β The sign stays the same, so handle it once and reverse the absolute value.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What must Reverse Integer return when the reversed number does not fit in a signed 32-bit integer?
Why: The rules say to return 0 when the reversed value overflows the signed 32-bit range.
- 2
How do you pull the last digit off a number using arithmetic?
Why: x % 10 gives the remainder after dividing by ten, which is the last digit.
- 3
Why must the overflow check happen before the multiply?
Why: After overflow the stored value is wrong, so you must compare against the limit before multiplying.
- 4
What does rev = rev * 10 + digit do?
Why: Multiplying by ten opens the ones place, then adding the digit fills it, building the reversed number.