DEV Community

Cover image for How to reverse an integer in Python | LeetCode Practice
Maria
Maria

Posted on

How to reverse an integer in Python | LeetCode Practice

In this post I am going to go though my solution for this exercise on LeetCode where you have to reverse an integer.

Examples:

  • 123 -> 321
  • -123 -> -321
  • 120 -> 21

Constrains:
If the integer is outside the range [−2**31, 2**31 − 1] return 0.

Have a go at it and let's compare our solutions!

Solution

First I will post my solution then go though the reasoning behind it:

def reverse(self, x: int) -> int:   

        if x < 0:
            x = str(x)[1:][::-1]

            while x[0] == '0':
                x = x[1:]

            x = 0-int(x)

            if x < -2**31:
                return 0

            return x

        else:
            if x <10:
                return x

            x = str(x)[::-1]

            while x[0] == '0':
                x = x[1:]

            x = int(x)

            if x > (2**31)-1:
                return 0

            return x
Enter fullscreen mode Exit fullscreen mode

I've chosen to tackle this in 2 scenarios: when x < 0 and when x is >=0. Let's start with x < 0.

First we turn x into a string, remove the '-' and reverse it. All of that is being taken care of by this line:

x = str(x)[1:][::-1]
Enter fullscreen mode Exit fullscreen mode

An example of what the above line does: -123 -> '-123' -> '123' -> '321'

If the new string has '0' at the beginning, we use a while loop to remove all the zeros until we find a non-zero character:

while x[0] == '0':
    x = x[1:]
Enter fullscreen mode Exit fullscreen mode

Then we turn x back into a negative integer and check if it is within the size constraint. If it is we return x otherwise we return 0:

x = 0-int(x)  
if x < -2**31:
   return 0

return x
Enter fullscreen mode Exit fullscreen mode

Next we will look at the case when x >= 0.

If x <10 this means that is a single digit letter, it reversed would just be itself, so we return it:

if x <10:
   return x
Enter fullscreen mode Exit fullscreen mode

Next we follow the same logic as above. We turn it into a string and reverse it:

x = str(x)[::-1]
Enter fullscreen mode Exit fullscreen mode

We strip it of 0s if there are any at the beginning of the string:

while x[0] == '0':
    x = x[1:]
Enter fullscreen mode Exit fullscreen mode

We turn it back into an integer and check against the constrains. If it doesn't meet the size requirements we return 0, otherwise return x:

x = int(x)

if x > (2**31)-1:
    return 0

return x
Enter fullscreen mode Exit fullscreen mode

This was my solution, let me know if you had a different one!

Also if you want you can follow me here or on Twitter :)

Top comments (2)

Collapse
 
jingxue profile image
Jing Xue

You could reverse and remove the leading zeroes in one step: str(int(str(x)[::-1])).

Collapse
 
mariamodan profile image
Maria

That's a great catch thanks for sharing!