DEV Community

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

Posted on

1 1

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 :)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

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!

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay