Reverse Integer
The drill: Reverse the digits of a signed 32-bit integer — and if the flipped result would overflow that range, hand back 0 instead of the wrong number.
A signed 32-bit integer arrives, and its digits need to come back in reverse order, sign preserved, as a fresh signed integer.
If flipping the digits would push the result outside the signed 32-bit range, the correct response is to hand back 0 instead of the wrapped or overflowed value.
Trailing zeros in the original number simply disappear once reversed, since a leading zero isn't a real digit — and the sign always stays attached to the number itself, never flipping independently.
- the input is a signed integer within the standard 32-bit range
- the output must also fit the signed 32-bit range, or the answer is 0
- the sign of the input carries through unchanged to the output
- leading zeros produced by the reversal are simply dropped
HINT 1 THE NUDGE
Turning the number into a string, reversing it and parsing it back gets the digits right — but that only works because the reversed value still fits somewhere your language can hold it.
HINT 2 THE STRUCTURE
Overflow has to be caught before it happens, not after — once a 32-bit value has already wrapped around, the number sitting in front of you is lying about what it represents.
HINT 3 ONE STEP FROM THE ANSWER
Build the reversed number one digit at a time; before every multiply-and-add step, check whether it would push past INT_MAX or below INT_MIN, and bail out to 0 right there.
123 — peel digits off the end with %10 and //10, checking the overflow boundary before every multiply-and-add.
class Solution:
def reverse(self, x: int) -> int:
INT_MIN, INT_MAX = -2**31, 2**31 - 1
sign = -1 if x < 0 else 1
x = abs(x)
result = 0
while x:
digit = x % 10
x //= 10
if result > (INT_MAX - digit) // 10:
return 0
result = result * 10 + digit
result *= sign
if result < INT_MIN or result > INT_MAX:
return 0
return resultclass Solution:
def reverse(self, x: int) -> int:
sign = -1 if x < 0 else 1
reversed_val = sign * int(str(abs(x))[::-1])
if reversed_val < -2**31 or reversed_val > 2**31 - 1:
return 0
return reversed_valclass Solution {
public int reverse(int x) {
int sign = x < 0 ? -1 : 1;
long remaining = Math.abs((long) x);
int result = 0;
while (remaining != 0) {
int digit = (int) (remaining % 10);
remaining /= 10;
if (result > (Integer.MAX_VALUE - digit) / 10) {
return 0;
}
result = result * 10 + digit;
}
return result * sign;
}
}class Solution {
public int reverse(int x) {
int sign = x < 0 ? -1 : 1;
String digits = new StringBuilder(String.valueOf(Math.abs((long) x))).reverse().toString();
long reversedVal = sign * Long.parseLong(digits);
if (reversedVal < Integer.MIN_VALUE || reversedVal > Integer.MAX_VALUE) {
return 0;
}
return (int) reversedVal;
}
}✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED