NeetCode #864LC-7MediumBit ManipulationNC 150NC 250
← Back to All Problems

#864 · #7 · Reverse Integer(整数反转)

📌 Problem Statement & Constraints

Given a signed 32-bit integer x, return x with its digits reversed. If the reversed value falls outside the signed 32-bit range [-2^31, 2^31 - 1], return 0 instead. Constraints: -2^31 <= x <= 2^31 - 1, and the environment cannot store 64-bit integers.

💡 Core Algorithmic Approaches

  1. Pop digits from the right with x % 10 and push them onto the result with res = res * 10 + digit.
  2. Because Python has arbitrary precision, the 32-bit overflow must be checked explicitly rather than left to the machine.
  3. Check before multiplying: the operation is safe only while res <= (INT_MAX - digit) // 10.
  4. Handle the sign separately by working with abs(x) and re-applying the sign at the end.

💻 Benchmark Python3 Implementation

class Solution:
    def reverse(self, x: int) -> int:
        INT_MAX = 2**31 - 1
        sign = -1 if x < 0 else 1
        x = abs(x)
        res = 0
        while x:
            digit = x % 10
            x //= 10
            if res > (INT_MAX - digit) // 10:   # the next multiply would overflow
                return 0
            res = res * 10 + digit
        return sign * res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(log |x|): one iteration per decimal digit.
💾 Space Complexity
O(1): a few scalars.

⚠️ Interview Pitfalls & Follow-ups

  • Checking overflow after the multiply: the multiply itself is the overflow, so the guard must come first.
  • Using int(str(x)[::-1]): it ignores the overflow rule the problem is testing and mishandles the leading minus sign.
  • Taking x % 10 on a negative number in Python: Python's modulo is non-negative, so -123 % 10 is 7, not -3; use abs first.
  • Clamping instead of returning 0: LeetCode expects exactly 0 on overflow.
  • Dropping trailing zeros incorrectly: 120 must become 21, which the digit-popping loop handles naturally.