Python Leetcode Grind

I need an excuse to get better at python. I naturally tend to do the hardest thing possible because that often is the best possible solution in the long run (no shortcuts). I don’t know if that’s a good philosophy in tech as it was in finance, but until I learn otherwise that’ll be my go-to strategy.

I figured the worst way to learn python is by grinding Leetcode so this will be a running document of my Leetcode successes or failures. No matter what I’ll post my answers and what I learned from other people’s answers.

7. Reverse Integer

9/18/2021 9am

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x==0:
            return 0
        elif x/abs(x) == -1:
            x=str(abs(x))[::-1]
            x = -1*int(x)
        else: 
            x=str(abs(x))[::-1]
            x = int(x)
        if x >= 2**31-1 or x <= -2**31:
            return 0
        return x

My answer is not elegant but it was not the worst in terms of memory or speed:

  • Runtime: Faster than 71% of python submissions
  • Memory Usage: Less than 65% of python submissions

Interesting Answer From Leetcode

def reverse(x):
    num = 0
    neg = False
    if x < 0:
        neg = True
        x = x*(-1)
    while x >= 1:
        digit = x%10
        x = int(x/10)
        num = num*10+digit
    if neg:
        num=num*(-1)
    if not (-2)**31 < num < (2**31)-1 :
        num = 0
    return num

This was a good way to look at the problem mathematically. The main parts being the while statement:

  • x%10 takes the very last digit of x
  • x is divided by 10 and saved to x
  • multiply num which starts at 0 and add digit
    • this then becomes num for the next loop
  • Repeating this in the while loop makes
    • digit is the next digit because we divided by 10
    • num grows by 10 because of the formula to multiply by 10 and add digit

I’m very jealous of people who can think this way. The next two hours on this Saturday morning will be to grind Fluent Python by Luciano Ramalho.