Reverse Integer

Patrick Leaton
Problem Description

Given a 32-bit signed integer, reverse digits of an integer.

Note:
Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

 

Example 1:

Input: x = 123
Output: 321

Example 2:

Input: x = -123
Output: -321

Example 3:

Input: x = 120
Output: 21

Example 4:

Input: x = 0
Output: 0

Constraints:

  • -2^31 <= x <= 2^31 - 1

 

Description taken from https://leetcode.com/problems/reverse-integer/.

Problem Solution

#O(N) Time, O(1) Space
class Solution:
    def reverse(self, x: int) -> int:
        reversed_int = 0
        is_negative = x < 0
        x = abs(x)
        while x != 0:
            reversed_int *= 10
            reversed_int += x % 10
            x //= 10
        if reversed_int > 2**31:
            return 0
        if is_negative == True:
            return -reversed_int
        else:
            return reversed_int

Problem Explanation


We can solve this problem by taking advantage of the modulo and division operators.

Since we are dealing with a base-ten number, we will just need to iteratively chop off the last number of the digit until it goes to zero.  Through the modulo operator, we can isolate this value, and through the division operator we can chop it off. 


We will start by initializing our output integer to zero and checking if our input is negative.  We do this to know whether the returned integer will need to be negative as well. 

        reversed_int = 0
        is_negative = x < 0

 

We will then convert x to positive by taking the absolute value so we can process each digit individually. 

        x = abs(x)

 

Next, let's make a while loop for chopping off each digit from x. This will run until there are no more digits to chop.

        while x != 0:

 

Each iteration will start by multiplying the output integer by ten so that we will have a placeholder for the next digit. 

            reversed_int *= 10

 

We will then add the last digit of the current integer to our output by modulo x by ten, this way we extract only the last digit of x for each iteration.

            reversed_int += x % 10

 

After we have isolated the last digit of the current integer and added it to our output, we will chop off the digit by dividing the current integer by ten while also ensuring it does not convert to a float by using // instead of /.

            x //= 10

 

If our reversed integer is larger than a 32-bit signed integer, we will return zero since this number is invalid due to the problem description. 

        if reversed_int > 2**31:
            return 0

 

Otherwise, we return our reversed integer.  We will set it as negative if the initial input was negative.

        if is_negative == True:
            return -reversed_int
        else:
            return reversed_int