Medium

Reverse Integer

Description

Reverse the decimal digits of a signed 32-bit integer while preserving its sign. Return zero if the reversed number would leave the range -2147483648..2147483647. Avoid wider integer storage.

Solution

def reverse(x):
    result = 0
    while x:
        quotient = abs(x) // 10
        if x < 0:
            quotient = -quotient
        digit = x - quotient * 10
        x = quotient
        if result > 214748364 or (result == 214748364 and digit > 7):
            return 0
        if result < -214748364 or (result == -214748364 and digit < -8):
            return 0
        result = result * 10 + digit
    return result

Examples

Example 1

Input
[123]
Output
321

Reverse the digit order.

Example 2

Input
[-120]
Output
-21

Preserve the sign and discard leading zeros in the result.

Example 3

Input
[1534236469]
Output
0

The reversal exceeds the 32-bit maximum.

Approach

Extract signed digits by division and remainder, checking the result against the 32-bit limits before each multiply-by-ten and addition. Python explicitly computes truncation toward zero so negative inputs follow the same logic.

Time & space

O(d) time and O(1) auxiliary space, where d is the number of decimal digits, at most ten.