7. Reverse Integer - Explanation
Description
You are given a signed 32-bit integer x.
Return x after reversing each of its digits. After reversing, if x goes outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0 instead.
Solve the problem without using integers that are outside the signed 32-bit integer range.
Example 1:
Input: x = 1234
Output: 4321Example 2:
Input: x = -1234
Output: -4321Example 3:
Input: x = 1234236467
Output: 0Constraints:
-2^31 <= x <= 2^31 - 1
Topics
Recommended Time & Space Complexity
You should aim for a solution with O(1) time and O(1) space.
Hint 1
A straightforward approach would be to convert the given integer to a string, reverse it, convert it back to an integer using a long type, and return 0 if the result exceeds the integer range. Can you think of a better way?
Hint 2
We initially declare the result res as an int with a value of 0. We iterate through the given integer, extracting digits one by one. Before appending a digit to res, we consider multiple cases. Can you determine them? Maybe you should think about overflow.
Hint 3
Let MAX be the maximum positive integer and MIN be the minimum negative integer. We iterate through each digit and check for overflow before updating res. If res > MAX / 10 or res < MIN / 10, return 0. If res == MAX / 10 and the current digit is greater than MAX % 10, return 0. If res == MIN / 10 and the current digit is less than MIN % 10, return 0. Otherwise, append the digit to res and continue.
Prerequisites
Before attempting this problem, you should be comfortable with:
- Integer Arithmetic - Using modulo (%) to extract digits and integer division (/) to remove digits
- Overflow Detection - Understanding 32-bit signed integer bounds and checking for overflow before it occurs
- Handling Negative Numbers - Knowing how modulo and division behave differently for negative values across languages
1. Brute Force
Intuition
We want to reverse the digits of an integer x (for example, 123 -> 321, -120 -> -21).
A very simple way to do this is:
- ignore the sign for a moment and work with the absolute value
- convert the number to a string so digits become easy to manipulate
- reverse the string and convert it back to an integer
- restore the original sign if
xwas negative
Finally, the problem usually requires that the answer must fit in a 32-bit signed integer range:
- from
-2^31to2^31 - 1
If the reversed number goes outside this range, we return0.
This approach is beginner-friendly because it uses direct operations on strings instead of manual digit math.
Algorithm
- Save the original value of
xinorgso we remember its sign. - Convert
xto its absolute value. - Convert the number to a string.
- Reverse the string.
- Convert the reversed string back to an integer
res(this automatically removes leading zeros). - If the original number was negative, make
resnegative. - Check if
resfits in the 32-bit signed integer range:- If it does not, return
0.
- If it does not, return
- Otherwise, return the reversed number.
Time & Space Complexity
- Time complexity:
- Space complexity:
2. Recursion
Intuition
We want to reverse the digits of an integer while preserving its sign and ensuring the result fits within the 32-bit signed integer range.
Instead of reversing digits using strings, this approach uses pure arithmetic and recursion.
The idea is simple:
- Take the last digit of the number
- Append it to a running reversed value
- Remove the last digit from the number
- Repeat until the number becomes
0
Recursion naturally fits this process because each step reduces the problem size by one digit.
Algorithm
- Determine the sign of the number (
+or-) and work with its absolute value. - Define a recursive function
recthat takes:- the remaining number
n - the reversed number built so far
rev
- the remaining number
- Base case:
- If
nis0, returnrev.
- If
- Recursive step:
- Extract the last digit using modulo (
n % 10) - Append it to
rev(rev * 10 + digit) - Recurse on the remaining number (
n // 10)
- Extract the last digit using modulo (
- After recursion finishes:
- Restore the original sign.
- Check for 32-bit signed integer overflow:
- If overflow occurs, return
0.
- If overflow occurs, return
- Otherwise, return the reversed number.
class Solution:
def reverse(self, x: int) -> int:
def rec(n: int, rev: int) -> int:
if n == 0:
return rev
rev = rev * 10 + n % 10
return rec(n // 10, rev)
sign = -1 if x < 0 else 1
x = abs(x)
reversed_num = rec(x, 0)
reversed_num *= sign
if reversed_num < -(1 << 31) or reversed_num > (1 << 31) - 1:
return 0
return reversed_numTime & Space Complexity
- Time complexity:
- Space complexity:
3. Iteration
Intuition
We want to reverse the digits of an integer without using strings, while also ensuring the result fits within the 32-bit signed integer range.
The key idea is to build the reversed number digit by digit:
- Repeatedly take the last digit of the number
- Append it to the end of a running
res - Remove the last digit from the original number
However, before appending a new digit, we must check for overflow.
If multiplying res by 10 (and adding the new digit) would exceed the 32-bit signed integer limits, we immediately return 0.
This approach closely matches how integer reversal works at a low level and is both efficient and safe.
Algorithm
- Define constants:
MIN = -2^31MAX = 2^31 - 1
- Initialize
res = 0to store the reversed number. - While
xis not0:- Extract the last digit
digitofx. - Remove the last digit from
x. - Before updating
res, check:- If
res * 10 + digitwould overflow the 32-bit signed integer range:- Return
0.
- Return
- If
- Update
res = res * 10 + digit.
- Extract the last digit
- After the loop finishes, return
res.
class Solution:
def reverse(self, x: int) -> int:
MIN = -2147483648 # -2^31,
MAX = 2147483647 # 2^31 - 1
res = 0
while x:
digit = int(math.fmod(x, 10))
x = int(x / 10)
if res > MAX // 10 or (res == MAX // 10 and digit > MAX % 10):
return 0
if res < MIN // 10 or (res == MIN // 10 and digit < MIN % 10):
return 0
res = (res * 10) + digit
return resTime & Space Complexity
- Time complexity:
- Space complexity:
Common Pitfalls
Checking for Overflow After It Happens
A critical mistake is multiplying res by 10 and adding the digit before checking if the result overflows. By that point, overflow has already occurred and the value is corrupted. The overflow check must happen before the multiplication to determine if the next operation would exceed the 32-bit signed integer bounds.
Incorrect Handling of Negative Numbers with Modulo
Different programming languages handle the modulo operation differently for negative numbers. In Python, -123 % 10 returns 7, not -3. Using the wrong modulo behavior leads to incorrect digit extraction for negative inputs. Use language-specific functions like math.fmod() in Python or ensure consistent handling across languages.
Forgetting the Asymmetric Range of 32-bit Signed Integers
The 32-bit signed integer range is asymmetric: -2^31 to 2^31 - 1. This means the minimum value has a larger absolute value than the maximum. When checking for overflow, both boundaries must be validated separately. Simply checking against one limit and assuming symmetry causes edge cases like reversing 1534236469 to fail silently.
Sign in to join the discussion