Reverse Integer (LeetCode 7): Solution and Explanation
Given a signed 32-bit integer, return the integer formed by reversing its decimal digits, keeping the sign. If the reversed value falls outside the signed 32-bit range, return 0 instead.
Watch it run step by step
Try your own input and write the code →Intuition
The quick approach converts the number to a string, reverses it, and parses it back, taking care of the minus sign. That is short, but it relies on string handling and on being able to hold an out-of-range value before checking it. The arithmetic approach is just as easy and shows the pattern interviewers expect.
Reversing digits with arithmetic works like a stack. The last digit of x is x % 10, and removing it is x // 10. Pushing a digit onto the result is result * 10 + digit. Repeat until x runs out of digits, and the result holds the digits in reverse order. Trailing zeros of the input simply become leading zeros of the result and disappear, so 120 turns into 21.
Negative numbers need care because the modulo and floor division operators behave differently across languages for negative values. The Python reference avoids the issue by recording the sign, reversing the absolute value, and reapplying the sign at the end.
The last step is the range check. The reversed number of a valid 32-bit input can overflow, for example 1534236469 becomes 9646324351. Python integers never overflow, so the code builds the full value and compares it with -2³¹ and 2³¹ - 1. In Java or C++ you would instead check before each multiplication whether result is already beyond INT_MAX / 10, because the overflow would happen before you could test it.
Approach: Pop and push digits with a range check
- Record
signas -1 for negative inputs and 1 otherwise, then replacexwith its absolute value. - Start with
result = 0. - While
xis not zero, append its last digit withresult = result * 10 + x % 10. - Remove that digit from
xwithx //= 10. - Multiply
resultbysign. - If the value is below -2³¹ or above 2³¹ - 1, return 0; otherwise return it.
Step-by-step example
x = -123
- The sign is -1 and
xbecomes 123. - The last digit 3 is pushed, so
result = 3andx = 12. - Next, 2 is pushed, so
result = 32andx = 1. Then 1 is pushed, soresult = 321andx = 0. - Applying the sign gives -321, which is within the 32-bit range, so the function returns -321.
Code: Python, Java, C++
1class Solution:
2 def reverse(self, x: int) -> int:
3 sign = -1 if x < 0 else 1
4 x = abs(x)
5 result = 0
6
7 while x:
8 result = result * 10 + x % 10
9 x //= 10
10
11 result *= sign
12 if result < -2**31 or result > 2**31 - 1:
13 return 0
14 return result1class Solution {
2 public int reverse(int x) {
3 int sign = x < 0 ? -1 : 1;
4 long num = Math.abs((long) x);
5 long result = 0;
6
7 while (num > 0) {
8 result = result * 10 + num % 10;
9 num /= 10;
10 }
11
12 result *= sign;
13 if (result < Integer.MIN_VALUE || result > Integer.MAX_VALUE) return 0;
14 return (int) result;
15 }
16}1class Solution {
2public:
3 int reverse(int x) {
4 long result = 0;
5 while (x != 0) {
6 result = result * 10 + x % 10;
7 x /= 10;
8 }
9 if (result < INT_MIN || result > INT_MAX) return 0;
10 return result;
11 }
12};Time and space complexity
O(log |x|)
The loop runs once per decimal digit, and a number has about log₁₀ |x| digits, which is at most 10 for 32-bit inputs.
O(1)
Only a few integer variables are used.
Other approaches
String reversal (time O(log |x|), space O(log |x|))
Convert the absolute value to a string, reverse it, convert back, reapply the sign and check the range. It is short and readable but allocates strings and is less portable to strictly 32-bit environments.
In-loop overflow guard (time O(log |x|), space O(1))
Before each push, check whether result exceeds INT_MAX / 10, or equals it with a final digit above 7, and return 0 early. This is how the problem must be solved in languages with fixed-width integers, and it is the version interviewers usually push toward once you mention overflow.
Common mistakes
- Checking for overflow only after the loop in Java or C++. By then the value has already wrapped around, so the check never fires.
- Using
%and//directly on negative numbers in Python. -123 % 10 is 7 in Python, not -3, which corrupts the digits. - Forgetting that trailing zeros vanish. 120 reverses to 21, and that is the correct answer.
- Treating -2³¹ as safe to negate. Its absolute value does not fit in a 32-bit int, which matters in languages that store it in an
int.
Frequently asked questions
How do you check for overflow in Reverse Integer?
In fixed-width languages, check before each step whether result * 10 + digit would exceed the limit, by comparing result with INT_MAX / 10. In Python, you can build the full value and compare it with the 32-bit bounds afterward.
Why does 120 reverse to 21?
Reversing gives 021, and leading zeros have no value in an integer, so the result is 21.
What is the time complexity of Reverse Integer?
It is O(log |x|), one iteration per decimal digit, which is at most 10 iterations for 32-bit inputs. Space is O(1), because only the running result and the shrinking input are kept.
Why does the problem forbid 64-bit integers?
The restriction forces you to think about overflow the way you would in an embedded or performance-sensitive setting where a wider type is not available. The practical consequence is that the range check has to happen before each multiplication rather than at the end, using INT_MAX / 10 and INT_MIN / 10 as thresholds.