LeetEye LeetEye
Medium Bit Manipulation ~5 min

Reverse Integer

bit-manipulation reverse-integer

Problem

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers.

Examples

Example 1
Input: x = 123
Output: 321
Example 2
Input: x = -123
Output: -321
Example 3
Input: x = 120
Output: 21
Key Insight

Pop digits from end (mod 10), push to result (multiply by 10). Check overflow before each push.

Pop last digit (x % 10), push to result (rev * 10 + digit), remove from x (x // 10). Check overflow BEFORE each push.

How to Approach This Problem

Pattern Recognition: When you see keywords like reverse integer bit-manipulation, think Bit Manipulation.

Step-by-Step Reasoning

1 To get the last digit of x:
Answer: x % 10
Modulo 10 gives the ones digit.
2 To remove the last digit of x:
Answer: x // 10
Integer division by 10 drops the last digit.
3 To add digit d to reversed number rev:
Answer: rev * 10 + d
Shift existing digits left (multiply by 10), add new digit.
4 For 32-bit signed int, overflow if:
Answer: Either A or B
Must check BEFORE multiplying. If rev > MAX/10, rev*10 overflows. If rev == MAX/10, depends on digit.
5 For negative x:
Answer: B or C both work
In Python, -123 % 10 = 7 (weird). Better to track sign, work with absolute value.

Solution

def reverse(x: int) -> int:
    INT_MAX = 2**31 - 1
    INT_MIN = -2**31
    
    sign = 1 if x >= 0 else -1
    x = abs(x)
    rev = 0
    
    while x:
        digit = x % 10
        x //= 10
        
        # Check overflow before push
        if rev > INT_MAX // 10:
            return 0
        
        rev = rev * 10 + digit
    
    rev *= sign
    return rev if INT_MIN <= rev <= INT_MAX else 0

Complexity Analysis

Time O(log x)
Space O(1)

Master This Pattern

Build intuition with interactive MCQs. Practice Bit Manipulation problems in the LeetEye app.

Download LeetEye Free
Practice in LeetEye