Reverse Integer
You're given a signed 32-bit integer x. Return x with its digits reversed, keeping its sign. If the reversed value falls outside the signed 32-bit range [-2^31, 2^31 - 1], return 0. Assume you can't store 64-bit integers, so the overflow has to be caught before it happens.
Examples
x = 4071 returns 1704
The digits 4, 0, 7, 1 read back to front are 1, 7, 0, 4.
x = -560 returns -65
The trailing zero becomes a leading zero and drops away, and the sign stays.
x = 2000000009 returns 0
The reversed value 9000000002 is larger than 2^31 - 1 = 2147483647, so the answer is 0.
Constraints
- -2^31 <= x <= 2^31 - 1
Hints
x % 10 gives the last digit and x / 10 drops it. How do you append a digit to the end of the result?
result = result * 10 + digit builds the reversed number. The only hard part is noticing an overflow before it happens.
With MAX = 2^31 - 1, return 0 before a push if result > MAX / 10, or if result == MAX / 10 and the digit is greater than 7. Mirror the check for negatives against MIN / 10 and -8.
Drill This: Your Approach First
Approach
Pop digits off the end of x with x % 10 and x / 10, and push each onto the result with result * 10 + digit. Check before every push: with MAX = 2^31 - 1, the push overflows when result > MAX / 10, or when result == MAX / 10 and the digit is above 7. The negative side mirrors this against MIN / 10 and -8. In Java, % and / truncate toward zero, so a negative x yields negative digits and one loop handles both signs. Python floors negative division, so the Python version reverses the absolute value and checks it against 2^31 - 1 or 2^31. O(log |x|) time, one step per digit, and O(1) space.
Time
O(log x)
Space
O(1)
Pitfall
Solutions
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;
}
}class Solution:
def reverse(self, x: int) -> int:
sign = -1 if x < 0 else 1
limit = 2**31 if x < 0 else 2**31 - 1
x = abs(x)
result = 0
while x:
digit = x % 10
x //= 10
if result > (limit - digit) // 10:
return 0
result = result * 10 + digit
return sign * result