Core Insight Use a bit operation to retain only the information the problem needs while discarding the rest.
Common Pitfall Parenthesize shifts and masks, especially when mixing comparison or arithmetic operators.
Description
Reverse the digits of a 32-bit signed integer.
Constraints
- Time Complexity:
O(log n) - Space Complexity:
O(1)
Tags
mathbit-manipulation
Implementation Plan Translate the invariant into these small, testable moves.
- Choose the bitwise identity.
- Initialize the accumulator or mask.
- Apply the operation per value or bit.
- Interpret the resulting bits.
def reverse(x):
MIN = -2147483648
MAX = 2147483647
res = 0
while x:
digit = int(math.fmod(x, 10))
x = int(x / 10)
if (res > MAX // 10 or
(res == MAX // 10 and digit >= MAX % 10)):
return 0
if (res < MIN // 10 or
(res == MIN // 10 and digit <= MIN % 10)):
return 0
res = (res * 10) + digit
return res