Peel digits off the end of x with % 10 and // 10, and build the reversed number by appending each digit to a running total. The entire difficulty is the overflow check: Python integers grow arbitrarily large, so nothing stops them from exceeding the 32-bit range on their own — the problem’s “no 64-bit integers” constraint has to be enforced explicitly, by checking bounds even though Python would not naturally hit them.
String Reversal
Time O(log x)Space O(log x)Convert to a string, reverse it, and convert back, handling the sign separately so the minus sign is not reversed into the wrong place.
class Solution: def reverse(self, x: int) -> int: sign = -1 if x < 0 else 1 digits = str(abs(x))[::-1] result = sign * int(digits) INT_MAX, INT_MIN = 2**31 - 1, -2**31 if result < INT_MIN or result > INT_MAX: return 0 return resultFor x = 120: abs(x) = 120 reverses to the string "021", and int("021") == 21 — the leading zero is dropped automatically, correctly producing 21 instead of 210. The number of digits is O(log x), so building and reversing the string costs O(log x) time and space.
Digit-by-Digit with Explicit Overflow Check
OptimalTime O(log x)Space O(1)Build the reversed number arithmetically instead of through strings: repeatedly take x % 10 as the next digit and fold it into result = result * 10 + digit, while shrinking x with x // 10. Because Python has no fixed-width integers, the 32-bit overflow check must be done explicitly — comparing result against INT_MIN/INT_MAX after it is fully built, or (as here) checking after every digit so the accumulator itself never runs away.
class Solution: def reverse(self, x: int) -> int: INT_MAX, INT_MIN = 2**31 - 1, -2**31 sign = -1 if x < 0 else 1 x = abs(x) result = 0 while x: digit = x % 10 x //= 10 result = result * 10 + digit # Bail out early the moment the unsigned magnitude would overflow. if result > INT_MAX: return 0 result *= sign if result < INT_MIN or result > INT_MAX: return 0 return resultTracing x = -123: sign is -1, x becomes 123.
x=123: digit=3, x=12, result = 0*10+3 = 3x=12: digit=2, x=1, result = 3*10+2 = 32x=1: digit=1, x=0, result = 32*10+1 = 321x=0: loop ends -> result = 321 * sign(-1) = -321-321 is within [-2^31, 2^31 - 1], so the function returns -321. For an overflow case like x = 1534236469, the digits reverse to 9646324351, which exceeds 2^31 - 1 = 2147483647 — the result > INT_MAX check fires mid-loop and the function returns 0 immediately, without ever needing 64-bit storage.
Complexity: one pass over the digits of x, O(1) work per digit → O(log x) time (the number of digits), O(1) extra space — strictly better than the string approach’s O(log x) space, and it enforces the “no 64-bit integers” constraint directly instead of relying on Python’s unbounded integers to happen to work out.