← DSA
MEDIUM

Reverse Integer

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.

Example

Input x = 123
Output 321

Key Pointers

Step-by-Step Analysis

  1. Record the sign of x, then continue working with abs(x).
  2. While the working value is nonzero: pop its last digit with % 10, append it to result (result = result * 10 + digit), then drop the digit with integer division by 10.
  3. Reapply the sign to result.
  4. If result falls outside [-2^31, 2^31 - 1], return 0; otherwise return result.

Complexity

Time: O(d) where d is the number of digits — Space: O(1)

Code

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 result

Code Explanation

How the solution above works, piece by piece.

  1. Remember the sign and work with abs(x).
  2. x % 10 is the last digit; result * 10 + digit appends it to the reversed number.
  3. x //= 10 drops that digit.
  4. Re-apply the sign. If the result is outside the signed 32-bit range [−2³¹, 2³¹ − 1], return 0 as the problem requires.
  5. O(number of digits) = O(log x).

Visual Walkthrough

Running it on x = 123:

trace3take 3result = result × 10 + 3 = 3; x → 1232take 2result = result × 10 + 2 = 32; x → 1321take 1result = result × 10 + 1 = 321; x → 0321checkinside the 32-bit range → 321
Digits are peeled off the right of x and pushed onto the right of result, which reverses their order.

Video Explanation

NeetCode — Bit Manipulation, LeetCode 7