Reverse Integer

Medium · Bit Manipulation · Explanation and code example

Iteration

How it works

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.

Steps

  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.

Complexity

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

Things to watch for

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.

Python code example

import math

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

C++ code example

class Solution {
public:
    int reverse(int x) {
        const int MIN = -2147483648; // -2^31
        const int MAX = 2147483647;  // 2^31 - 1

        int res = 0;
        while (x != 0) {
            int digit = x % 10;
            x /= 10;

            if (res > MAX / 10 || (res == MAX / 10 && digit > MAX % 10))
                return 0;
            if (res < MIN / 10 || (res == MIN / 10 && digit < MIN % 10))
                return 0;
            res = (res * 10) + digit;
        }

        return res;
    }
};
Source and license

Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.

Your recall check is in progress. Write your attempt before revealing the explanation.

Resume recall check

Browse all problem explanations