7. Reverse Integer - Explanation

Problem Link

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: 4321

Example 2:

Input: x = -1234

Output: -4321

Example 3:

Input: x = 1234236467

Output: 0

Constraints:

  • -2^31 <= x <= 2^31 - 1


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.


Company Tags

Please upgrade to NeetCode Pro to view company tags.



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 x was negative

Finally, the problem usually requires that the answer must fit in a 32-bit signed integer range:

  • from -2^31 to 2^31 - 1
    If the reversed number goes outside this range, we return 0.

This approach is beginner-friendly because it uses direct operations on strings instead of manual digit math.

Algorithm

  1. Save the original value of x in org so we remember its sign.
  2. Convert x to its absolute value.
  3. Convert the number to a string.
  4. Reverse the string.
  5. Convert the reversed string back to an integer res (this automatically removes leading zeros).
  6. If the original number was negative, make res negative.
  7. Check if res fits in the 32-bit signed integer range:
    • If it does not, return 0.
  8. Otherwise, return the reversed number.
class Solution:
    def reverse(self, x: int) -> int:
        org = x
        x = abs(x)
        res = int(str(x)[::-1])
        if org < 0:
            res *= -1
        if res < -(1 << 31) or res > (1 << 31) - 1:
            return 0
        return res

Time & Space Complexity

  • Time complexity: O(1)O(1)
  • Space complexity: O(1)O(1)

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

  1. Determine the sign of the number (+ or -) and work with its absolute value.
  2. Define a recursive function rec that takes:
    • the remaining number n
    • the reversed number built so far rev
  3. Base case:
    • If n is 0, return rev.
  4. Recursive step:
    • Extract the last digit using modulo (n % 10)
    • Append it to rev (rev * 10 + digit)
    • Recurse on the remaining number (n // 10)
  5. After recursion finishes:
    • Restore the original sign.
  6. Check for 32-bit signed integer overflow:
    • If overflow occurs, return 0.
  7. 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_num

Time & Space Complexity

  • Time complexity: O(1)O(1)
  • Space complexity: O(1)O(1)

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

  1. Define constants:
    • MIN = -2^31
    • MAX = 2^31 - 1
  2. Initialize res = 0 to store the reversed number.
  3. While x is not 0:
    • Extract the last digit digit of x.
    • Remove the last digit from x.
    • Before updating res, check:
      • If res * 10 + digit would overflow the 32-bit signed integer range:
        • Return 0.
    • Update res = res * 10 + digit.
  4. 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 res

Time & Space Complexity

  • Time complexity: O(1)O(1)
  • Space complexity: O(1)O(1)