Browse curriculum

Reverse Integer (LeetCode 7)

Reverse Integer (LeetCode 7): reverse the digits of a 32-bit integer by popping the last digit and pushing it onto the result, checking for overflow before each push.

Problem Understanding

Reverse Integer: given a signed 32-bit integer x, return x with its digits reversed. If the reversed value falls outside [-2^31, 2^31 - 1], return 0. Assume you cannot store 64-bit integers.

Examples: 123 → 321, -123 → -321, 120 → 21.

The Intuition: Pop From One End, Push Onto the Other

Two arithmetic moves do the whole job:

  1. Pop the last digit of x: digit = x % 10, then x /= 10.
  2. Push it onto the end of result: result = result * 10 + digit.

Repeat until x is 0 and the digits come out reversed. The only hard part is the 64-bit ban: result * 10 can overflow before you get a chance to compare it. So compare first. INT_MAX is 2147483647, so if result is already above 214748364, or equal to it with a next digit above 7, the push would overflow. The same digit-at-a-time arithmetic underlies Pow(x, n), which reads the bits of n instead of decimal digits, and Plus One.

Reverse Integer Visualization

32-BIT RANGE: -2147483648 TO 2147483647

START

x

1
2
3

result

0

digit

:

pushed

0

 

x = 123, result = 0. Pop digits off the end of x and push them onto result

Next

Pop 3 (x is now 12). result = 0 × 10 + 3 = 3

Free preview: the first 3 of 5 steps

x

The top row is what is left of x; the bottom row is result, with the digit just pushed highlighted. Try Overflow to see the check stop the run, and Just fits for a reverse that lands 6 below the limit.

Reverse Integer Dry Run

Input: x = 120

Step digit x after result
1 0 12 0
2 2 1 2
3 1 0 21

Answer: 21. The trailing zero is pushed first, while result is still 0, so it leaves no trace.

Reverse Integer LeetCode Solution

Java, C++ and C check both bounds before the push. Python reverses the absolute value and restores the sign. JavaScript numbers are exact well past 2^31, so it can push first and compare after.

Reverse Integer Code
1var reverse = function(x) {
2 const MAX = 2 ** 31 - 1, MIN = -(2 ** 31);
3 let result = 0;
4 while (x !== 0) {
5 const digit = x % 10;
6 x = Math.trunc(x / 10);
7 result = result * 10 + digit;
8 if (result > MAX || result < MIN) return 0;
9 }
10 return result;
11};

Reverse Integer in Python, Java, C++, TypeScript and C

Reverse Integer in Python
class Solution:
    def reverse(self, x: int) -> int:
        sign = -1 if x < 0 else 1
        x, result = abs(x), 0
        while x:
            digit = x % 10
            x //= 10
            if result > (2**31 - 1 - digit) // 10:
                return 0
            result = result * 10 + digit
        return sign * result
Reverse Integer in Java
class Solution {
    public int reverse(int x) {
        int result = 0;
        while (x != 0) {
            int digit = x % 10;
            x /= 10;
            if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && digit > 7)) return 0;
            if (result < Integer.MIN_VALUE / 10 || (result == Integer.MIN_VALUE / 10 && digit < -8)) return 0;
            result = result * 10 + digit;
        }
        return result;
    }
}
Reverse Integer in C++
class Solution {
public:
    int reverse(int x) {
        int result = 0;
        while (x != 0) {
            int digit = x % 10;
            x /= 10;
            if (result > INT_MAX / 10 || (result == INT_MAX / 10 && digit > 7)) return 0;
            if (result < INT_MIN / 10 || (result == INT_MIN / 10 && digit < -8)) return 0;
            result = result * 10 + digit;
        }
        return result;
    }
};
Reverse Integer in TypeScript
function reverse(x: number): number {
    const MAX = 2 ** 31 - 1, MIN = -(2 ** 31);
    let result = 0;
    while (x !== 0) {
        const digit = x % 10;
        x = Math.trunc(x / 10);
        result = result * 10 + digit;
        if (result > MAX || result < MIN) return 0;
    }
    return result;
}
Reverse Integer in C
int reverse(int x) {
    int result = 0;
    while (x != 0) {
        int digit = x % 10;
        x /= 10;
        if (result > INT_MAX / 10 || (result == INT_MAX / 10 && digit > 7)) return 0;
        if (result < INT_MIN / 10 || (result == INT_MIN / 10 && digit < -8)) return 0;
        result = result * 10 + digit;
    }
    return result;
}

Edge Cases & Common Mistakes

  • Checking after the multiply: in C, C++ and Java, result * 10 has already overflowed (undefined behaviour in C and C++), so the check comes too late.
  • INT_MIN: -2147483648 has no positive counterpart; taking abs of it overflows in fixed-width languages, so keep the sign in each digit instead.
  • Trailing zeros: 120 becomes 21, not 021.
  • Zero: the loop never runs and the answer is 0.
  • Using a 64-bit long and comparing at the end: works in practice, but breaks the stated constraint.

Summary

Pop the last digit with % 10 and / 10, push it onto result with * 10 +, and check against INT_MAX / 10 and INT_MIN / 10 before every push. Return 0 on overflow. O(log |x|) time, O(1) space.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Pop a digit

    digit = x % 10, then x /= 10 (truncating toward zero).

  2. Check before pushing

    If result * 10 + digit would leave the 32-bit range (compare result with INT_MAX / 10 and INT_MIN / 10), return 0.

  3. Push the digit

    result = result * 10 + digit. Repeat until x is 0, then return result.

Frequently asked questions

How do you detect overflow in Reverse Integer without 64-bit integers?

Check before multiplying: result * 10 + digit overflows when result > INT_MAX / 10, or result == INT_MAX / 10 and digit > 7 (INT_MAX ends in 7). On the negative side, check result < INT_MIN / 10, or equal with digit < -8 (INT_MIN ends in 8).


How are negative numbers handled in Reverse Integer?

In Java, C++, C and JavaScript, the % operator keeps the sign of x, so negative numbers produce negative digits and build up correctly. In Python, % is always non-negative, so reverse abs(x) and restore the sign at the end.


What happens to trailing zeros when reversing an integer?

They become leading zeros and disappear: 120 reverses to 21. Popping the trailing 0 first just multiplies result (which starts at 0) by 10, leaving no trace.


What is the time and space complexity of Reverse Integer?

Time complexity is O(log10 |x|) because there are at most 10 decimal digits in a 32-bit signed integer. Space complexity is O(1) auxiliary memory.

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description