Reverse Integer
Given a signed 32-bit integer x, return x with its digits in reverse order. If the reversed number falls outside the 32-bit range [-2^31, 2^31 - 1], return 0 instead.
Assume you can't store any value outside that range, even temporarily, so you can't build the reversed number in a 64-bit integer and check it afterward.
Example 1
Input: x = -123 Output: -321
The digits reverse and the sign stays in front.
Example 2
Input: x = 1534236469 Output: 0
Reversed, this is 9646324351, which is larger than 2^31 - 1 = 2147483647.
Constraints
-2^31 <= x <= 2^31 - 1
Approach
Converting to a string and back is the quick way out, but it hides the real question: detecting overflow without ever holding a value that's too big. Build the answer one digit at a time instead.
Each step pops the last digit with x % 10 and pushes it onto result with result * 10 + digit. The push is the only step that can overflow, so check it before doing it. If result is already greater than INT_MAX / 10, multiplying by 10 overflows no matter which digit comes next. If result equals INT_MAX / 10, it overflows only when the digit is greater than 7, the last digit of 2147483647. The negative side mirrors this with INT_MIN / 10 and -8.
In Java, C++ and JavaScript, % and integer division truncate toward zero, so negative inputs produce negative digits and the sign takes care of itself. Python rounds toward negative infinity, so the Python solution reverses the absolute value and puts the sign back at the end.
Steps
- Set
resultto0. - While
xisn't0, take its last digit and remove it fromx. - If appending the digit would pass the 32-bit limit, return
0. - Otherwise set
resulttoresult * 10 + digit. - Return
result.
def reverse_integer(x: int) -> int:
INT_MAX = 2**31 - 1 # 2147483647
sign = -1 if x < 0 else 1
x = abs(x)
limit = INT_MAX if sign == 1 else INT_MAX + 1 # the negative range reaches one further
result = 0
while x:
digit = x % 10
x //= 10
# Stop before result * 10 + digit would go past the limit.
if result > (limit - digit) // 10:
return 0
result = result * 10 + digit
return sign * resultComplexity
- Time:
O(log |x|). There's one step per digit, at most 10. - Space:
O(1).
Common mistakes
- Checking
result * 10 + digit > INT_MAXafter computing it. In Java and C++ the overflow has already happened by then. - Forgetting the negative side.
-2147483648reverses to-8463847412, which is out of range too. - Using Python's
%on a negative number and getting a positive digit back, which flips the answer's sign.
int reverse(int x) { int rev = 0; bool isNegative = false; if(x < 0){ isNegative= true; x = abs(x); } while(x > 0){ int r = x % 10; rev = rev * 10 + r; x = x / 10; } if(isNegative){ return -rev; } return rev; }