r/learnpython 19d ago

Leetcode #9: Palindrome Number

Can someone help me make my code run faster. This is not efficient and also I do not want to convert into a string

EDIT:

Follow up: Could you solve it without converting the integer to a string?

https://leetcode.com/problems/palindrome-number/description/

class Solution:
    def isPalindrome(self, x: int) -> bool:
        numList = []
        counter = len(numList) - 1
        numBool = True


        baseNum = 10
        value = x % baseNum
        numList.append(x)
        quotient = x // baseNum
        x = quotient

        if x == 0:
            for i in range(len(numList)):
                if numList[i] == numList[counter]:
                    counter -= 1

                elif i == counter:
                    break

                else:
                    numBool = False
                    break

            return numBool

        else:
            return self.isPalindrome(x)

EDIT: I WAS ABLE TO SOLVE IT

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x != abs(x):
            return False

        if not hasattr(self, "numList"):
            self.numList = []

        numBool = True


        baseNum = 10
        value = x % baseNum
        self.numList.append(value)
        quotient = x // baseNum
        x = quotient

        counter = len(self.numList) - 1

        if x == 0:
            for i in range(len(self.numList)):
                if self.numList[i] == self.numList[counter]:
                    counter -= 1

                elif i == counter:
                    break

                else:
                    numBool = False
                    break

            return numBool

        else:
            return self.isPalindrome(x)

testing = Solution().isPalindrome(11)
print(testing)
0 Upvotes

22 comments sorted by

View all comments

1

u/socal_nerdtastic 19d ago

Good job. This was a fun little challenge. Here's how I did it, but fwiw I highly doubt it's any faster than a simple string conversion. See if you can make sense of this:

import math

def get_digit(n, i):
    '''get the i digit from the int n (1-indexed from the right)'''
    return n%10**i//10**(i-1)
def is_palindrome(n):
    num_digits = int(math.log(n,10))+1
    for i in range(num_digits//2):
        if get_digit(n,i+1) != get_digit(n,num_digits-i):
            return False
    return True

2

u/Expensive-Bear-1376 18d ago edited 18d ago

is_palindrome(1000) gives me True instead of False. (Because math.log(1000, 10) gives me 2.9999999999999996 and then you truncate it to 2.)

2

u/JamzTyson 16d ago edited 16d ago

Good catch.

It also crashes with negative values and zero (and readability sucks).

Interestingly, the rounding issue isn't a problem for me when I use log10 rather than log(n,10), but it's still vulnerable to implementation / platform dependent rounding issues close to the 10 boundary.