Hide sidebar

Reverse Integer

Reverse Integer

Math
MediumLeetCode #7
15 min

Problem Statement

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

Examples

Example 1:

Input: x = 123

Output: 321

Example 2:

Input: x = -123

Output: -321

Example 3:

Input: x = 120

Output: 21

Solution (Pop and Push Digits)

We can reverse the integer by repeatedly "popping" the last digit from the input number and "pushing" it to the back of the result.

The main challenge is handling potential overflow. Before we "push" a new digit, we must check if doing so would exceed the 32-bit integer limits.

Algorithm Steps

  • Initialize reversed = 0.
  • While x is not 0:
  • Pop the last digit: digit = x % 10.
  • Update x = x / 10.
  • Before pushing the digit, check for overflow. If reversed > MAX / 10 or (reversed == MAX / 10 and digit > 7), it will overflow. Same logic applies for the minimum value.
  • Push the digit: reversed = reversed * 10 + digit.
  • Return reversed.

Current x

123

Reversed

0

Initial state: x = 123
Reverse Integer Solution

class Solution:
    def reverse(self, x: int) -> int:
        reversed_x = 0
        sign = 1 if x >= 0 else -1
        x = abs(x)
        
        while x != 0:
            digit = x % 10
            
            # Check for overflow before the multiplication
            if reversed_x > (2**31 - 1) // 10:
                return 0
            if reversed_x == (2**31 - 1) // 10 and digit > 7:
                 return 0

            reversed_x = reversed_x * 10 + digit
            x //= 10
            
        return sign * reversed_x