Hide sidebar

Reverse Integer

Reverse Integer

Math
MediumLeetCode #7
15 min

Problem Statement

Given a signed 32-bit integer x, reverse digits of an integer. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

Example

Example 1:

Input: x = 123

123321

Output: 321

Solution (Pop and Push Digits)

To reverse an integer, we can repeatedly "pop" the last digit off the number and "push" it onto the back of a new reversed number. We must also be careful about potential integer overflow.

Algorithm Steps

  • Initialize a reversed variable to 0.
  • Loop while the input number x is not 0.
  • In each iteration, get the last digit of x (the "pop" operation).
  • Before adding the new digit to reversed, check if doing so would cause an overflow. If it would, return 0.
  • "Push" the popped digit onto reversed by multiplying it by 10 and adding the digit.
  • Remove the last digit from x.
  • After the loop, return the reversed number.

Remaining (x)

123

Reversed (rev)

0

Start with x = 123.
Reverse Integer Solution

class Solution:
    def reverse(self, x: int) -> int:
        sign = -1 if x < 0 else 1
        x *= sign
        
        rev = 0
        while x > 0:
            rev = rev * 10 + x % 10
            x //= 10
            
        if rev > 2**31 - 1:
            return 0
            
        return rev * sign