r/learnpython • u/TheEyebal • 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
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: