PracticeNeetCode ↗LeetCode ↗
Given a signed 32-bit integer x, return x with its digits reversed. If reversing pushes the value outside the signed 32-bit range [-2^31, 2^31 - 1], return 0.
% 10 and // 10, building the reversed number one digit at a time — no need to convert to a string.x, then continue working with abs(x).% 10, append it to result (result = result * 10 + digit), then drop the digit with integer division by 10.result.result falls outside [-2^31, 2^31 - 1], return 0; otherwise return result.Time: O(d) where d is the number of digits — Space: O(1)
def reverse(x: int) -> int:
sign = -1 if x < 0 else 1
x = abs(x)
result = 0
while x:
result = result * 10 + x % 10
x //= 10
result *= sign
if result < -2**31 or result > 2**31 - 1:
return 0
return resultHow the solution above works, piece by piece.
abs(x).x % 10 is the last digit; result * 10 + digit appends it to the reversed number.x //= 10 drops that digit.Running it on x = 123:
x and pushed onto the right of result, which reverses their order.