15% off all plans & roadmaps Use code

See plans

Reverse Integer

Updated

TL;DR: Reverse the decimal digits of a 32-bit integer and return 0 if the result leaves the 32-bit range. Pop digits with % 10, push them onto a result, and test for overflow before each push.

Problem

Given a signed 32-bit integer x, return x with its decimal digits in reverse order. The sign stays in front of the reversed digits, and any leading zeroes in the reversed number disappear.

A signed 32-bit integer ranges from -2^31 through 2^31 - 1, inclusive. If the reversed value falls outside that range, return 0. Assume the environment cannot store 64-bit integers.

Example 1

Input: x = 12030
Output: 3021
Explanation: Reversing the digits gives 03021, which is the integer 3021 once the leading zero is dropped.

Example 2

Input: x = -804
Output: -408
Explanation: The digits 804 reverse to 408, and the negative sign stays in front.

Example 3

Input: x = 2147483641
Output: 1463847412
Explanation: The reversed value fits in the 32-bit signed range, so it is returned as is.

Constraints

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

Constraints that matter

  • x is a 32-bit integer, so it has at most 10 digits. Any digit-by-digit method runs in at most 10 iterations, so speed is never the issue.
  • The result must also fit in 32 bits. A 10-digit input can reverse into a number up to about 9.9 billion, so overflow is a real outcome, not a rare one.
  • The range is asymmetric: the minimum is -2147483648 and the maximum is 2147483647. The input -2147483648 cannot be negated inside a 32-bit int.
  • The statement assumes no 64-bit integers. That forces you to detect overflow before it happens instead of widening the type.

View on LeetCode

Hints

Hint 1

This is a reversal problem, so the pattern is two pointers on a string: read from one end, write to the other.

Hint 2

Turn the number into text, reverse the text, turn it back into a number, and compare against the range.

Solution

Intuition

This is a reversal problem, so the pattern is two pointers on a string: read from one end, write to the other. A number has no indexes, but arithmetic gives you both ends. x % 10 reads the last digit, and x / 10 removes it. Then result * 10 + digit appends that digit to the other side of the answer.

Picture a stack of coins where you move the top coin from one pile onto a second pile, one at a time. The first coin you move ends up at the bottom of the second pile, which is the most significant digit of the result.

The repeated pop and push is all the reversal there is. The first digit you pop is the last digit of x, and it ends up being the most significant digit of the result because every later push multiplies it by 10. Leading zeroes vanish on their own. The popped zeroes at the end of 12030 add 0 to a result that is still 0, so they never show up.

The hard part is the range check. A 10-digit input can reverse into an 11-digit-sized value, and in Java, C++ and C# the multiplication wraps or is undefined before you can compare. So you test whether result * 10 + digit would fit before you compute it. You compare result against the limit divided by 10, which never overflows.

Signs add one more wrinkle. In Java, C++, C# and Go, % and / truncate toward zero, so a negative x produces negative digits and a negative result. You can then check both bounds on the signed value without ever taking an absolute value, which matters because abs(-2147483648) does not fit in an int.

Watch the pattern animation

Worked example

Input: x = -2147483648
Output: 0
Explanation: The digits of 2147483648 reverse to 8463847412. With the sign restored that is -8463847412, which is far below -2^31, so the answer is 0.
String Reversal pattern infographic for Reverse Integer

Solution pattern

String Reversal

Part of Two Pointers

Approach 1: Brute force: reverse the stringString Reversal

Turn the number into text, reverse the text, turn it back into a number, and compare against the range. This is what most people write first, and it is correct as long as the parse step cannot overflow.

Strip the sign first and work on the absolute value as a wider integer. Reverse the digit characters, parse them, put the sign back, and return 0 when the value is outside 32 bits.

Steps

  1. Remember whether x is negative and take its absolute value in a 64-bit type.
  2. Convert the absolute value to a decimal string.
  3. Reverse the characters of the string.
  4. Parse the reversed string back into a 64-bit integer.
  5. Reapply the sign.
  6. Return 0 if the value is below -2^31 or above 2^31 - 1, otherwise return it.

Dry run

Take x = -2147483648.

  • The sign is negative and the absolute value is 2147483648.
  • The string is 2147483648, and reversed it is 8463847412.
  • Parsing gives 8463847412, and the sign makes it -8463847412.
  • That is below -2147483648, so the function returns 0.

Complexity

TimeO(d)
SpaceO(d)

Let d be the number of digits in x, at most 10. Building the string, reversing it and parsing it each touch every character once, so time is O(d). The string and its reversed copy hold d characters, so space is O(d), which is a constant 10 here.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def reverse(self, x: int) -> int:
        sign = -1 if x < 0 else 1
        # reverse the digit string of the absolute value
        r = sign * int(str(abs(x))[::-1])
        if r < -2**31 or r > 2**31 - 1:
            return 0
        return r

Approach 2: Digit loop with a 64-bit accumulator

What's slow: the string approach allocates text and parses it, which is work the arithmetic can do directly. It also needs a wide integer type to hold the reversed value before the range check.

The insight that fixes it: pop digits with % 10 and / 10, and push them with result * 10 + digit. Keep the accumulator in a 64-bit type so it cannot overflow in 10 steps, then compare against the 32-bit range once at the end.

This removes the string, but it still relies on a 64-bit integer, which the problem says you cannot assume.

Steps

  1. Record the sign and take the absolute value in a 64-bit integer.
  2. Start result at 0 as a 64-bit integer.
  3. While the value is above 0, pop its last digit with % 10.
  4. Divide the value by 10 to drop that digit.
  5. Set result = result * 10 + digit.
  6. Reapply the sign.
  7. Return 0 if the signed result is outside the 32-bit range, otherwise return it.

Dry run

Take x = -2147483648. The absolute value is 2147483648 and the sign is negative.

  • Popped digits in order: 8, 4, 6, 3, 8, 4, 7, 4, 1, 2.
  • The accumulator grows: 8, 84, 846, 8463, 84638, 846384, 8463847, 84638474, 846384741, 8463847412.
  • The loop ends when the value reaches 0. Applying the sign gives -8463847412.
  • That is outside the 32-bit range, so the function returns 0.

Complexity

TimeO(d)
SpaceO(1)

Let d be the number of digits in x, at most 10. Each iteration removes exactly one digit, so the loop runs d times with constant work per pass. The only storage is the value, the accumulator and the sign, so space is O(1). The accumulator never exceeds 9999999999, which fits in 64 bits.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def reverse(self, x: int) -> int:
        sign = -1 if x < 0 else 1
        n = abs(x)
        result = 0
        while n:
            result = result * 10 + n % 10  # push the popped digit
            n //= 10
        result *= sign
        if result < -2**31 or result > 2**31 - 1:
            return 0
        return result

Approach 3: Pop and push with a pre-overflow checkOptimal

What's slow: nothing in time, but the previous version breaks the rule of the problem. It needs a type wider than 32 bits to hold an intermediate value that may not fit.

The insight that fixes it: test whether the next push fits before you do it. A push computes result * 10 + digit. That stays at or below 2147483647 exactly when result is at most 214748364, and when result equals 214748364 the digit is at most 7. Comparing result with 214748364 involves no multiplication, so it cannot overflow.

For Java, C++, C# and Go, keep the sign inside the digits. Truncating division makes every digit of a negative x negative, so the same loop handles both signs. The lower bound is symmetric to the upper one: result must be at least -214748364, and at that value the digit must be at least -8. No absolute value is needed, so -2147483648 is safe.

Why it is correct. After each step, result holds the reversed form of every digit popped so far, and x holds the digits not yet popped. The check runs before each push, so result never leaves the 32-bit range, and the test is exact because a push fits precisely when the new value fits. When the check fires, the true reversed value is out of range, so returning 0 is the correct answer.

Steps

  1. Start with result = 0.
  2. While x is not 0, take digit = x % 10 and set x = x / 10 with truncation toward zero.
  3. If result > 214748364, or result == 214748364 and digit > 7, return 0.
  4. If result < -214748364, or result == -214748364 and digit < -8, return 0.
  5. Set result = result * 10 + digit.
  6. When the loop ends, return result.

Dry run

Take x = -2147483648. Digits come out negative because division truncates toward zero. The limit used for the check is -214748364.

Stepx beforedigitresult beforeCheckresult after
1-2147483648-80ok-8
2-214748364-4-8ok-84
3-21474836-6-84ok-846
4-2147483-3-846ok-8463
5-214748-8-8463ok-84638
6-21474-4-84638ok-846384
7-2147-7-846384ok-8463847
8-214-4-8463847ok-84638474
9-21-1-84638474ok-846384741
10-2-2-846384741below -214748364return 0

On step 10 the check fails before the multiply, so the function returns 0, which matches the expected output.

Complexity

TimeO(d)
SpaceO(1)

Let d be the number of digits in x, at most 10. Each pass removes one digit and does a fixed number of comparisons and one multiply-add, so time is O(d). Only x, digit and result are stored, so space is O(1). Every multiply-add runs only after the check proves it fits, so no intermediate value leaves the 32-bit range.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def reverse(self, x: int) -> int:
        # Python % and // floor toward negative infinity, so split the sign off
        sign = -1 if x < 0 else 1
        n = abs(x)
        limit = 2**31 if sign < 0 else 2**31 - 1
        result = 0
        while n:
            digit = n % 10
            n //= 10
            # result * 10 + digit <= limit  <=>  result <= (limit - digit) // 10
            if result > (limit - digit) // 10:
                return 0
            result = result * 10 + digit
        return sign * result

Common mistakes

  • Checking the range after result = result * 10 + digit. In Java, C++ and C# the value has already wrapped or is undefined behavior by then. Compare result with 214748364 before the multiply.
  • Writing x = abs(x) for a negative input in a 32-bit type. The value -2147483648 has no positive counterpart in an int. Keep the sign in the digits, or widen to a long first.
  • Using one bound for both signs, such as 2147483647 for negatives. The negative side allows a final digit of 8, so -2147483648 is a valid result. Check the upper and lower bounds separately.
  • Using x % 10 and x // 10 in Python on a negative x. Python floors, so -804 % 10 is 6 and -804 // 10 is -81, which breaks the digits. Take the absolute value and reapply the sign at the end.
  • Stripping leading zeroes by hand. Reversing 12030 pushes a 0 onto an accumulator that is still 0, so the zero costs nothing. Extra zero-handling code only adds bugs.
  • Returning the clamped value, such as 2147483647, on overflow. The problem asks for 0 whenever the reversed value is out of range.

Edge cases

  • x = 0: the loop never runs and the result is 0.
  • x = 120: the reversed digits are 021, so the answer is 21.
  • x = -2147483648: the reversed value is out of range, so return 0. The code must not call abs on it in a 32-bit type.
  • x = 1534236469: it reverses to 9646324351, which is above 2147483647, so return 0.
  • x = 1463847412: it reverses to 2147483641, which is the largest nearby value that fits, so return it unchanged.
  • x = -2147483412: it reverses to -2143847412, which is inside the range, so return it with the negative sign.

Follow-ups interviewers ask

How would you do it if a 64-bit type were allowed?
Accumulate in a long and compare once at the end, as in the second approach. The reversed value of a 10-digit number is below 10^10, which fits in 64 bits, so there is no overflow risk to manage.
Why is the digit check against 7 and 8 never triggered for 32-bit inputs?
The last digit you pop is the leading digit of x, and for a 10-digit 32-bit value that digit is at most 2. The tail checks matter only if the input type were wider. They are harmless and make the function correct for the general bound.
Can you detect overflow after the multiply without a wider type?
Yes, by undoing the operation. Compute the new value, then check that (new - digit) / 10 == result. This works for wrapping arithmetic in Java and C#, but it is undefined behavior in C++ for signed ints, so the pre-check is the safe choice.

Reverse Integer FAQ

What is the time complexity of Reverse Integer?

It is O(d), where d is the number of digits in x. A 32-bit integer has at most 10 digits, so in practice it is a constant 10 iterations. Space is O(1) for the digit-loop approaches.

Why use a pre-overflow check for Reverse Integer?

Because the multiply in result * 10 + digit is where overflow happens. If you compare result with 214748364 first, you reject bad values without computing them. That is the only way to stay inside 32 bits with no wider type.

How do you reverse an integer without converting it to a string?

Pop the last digit with x % 10, drop it with x / 10, and push it with result * 10 + digit. Repeat until x is 0. The digits come out right to left, so they land in reversed order.

Can Reverse Integer be solved in O(1) extra space?

Yes. The digit-loop solutions use three integers: the remaining value, the current digit and the result. Only the string approach uses space that grows with the number of digits.

How do you solve Reverse Integer in Python?

Python integers never overflow, so the hard part is only the 32-bit range check. Take the sign and absolute value, build the reversal with % 10 and // 10, then return 0 if the signed result is below -2^31 or above 2^31 - 1. Avoid % and // on negative values because they floor.

How does the Java solution for Reverse Integer handle negative numbers?

Java truncates toward zero, so x % 10 is negative for a negative x and the accumulator stays negative. You then check both 214748364 and -214748364 as limits. No absolute value is taken, so Integer.MIN_VALUE is safe.

Asked at

See which companies ask this — Pro

Practise it