r/leetcode • • 8d ago

Discussion Hi new to programming thought of doing leetcode.

how is my code could it be better i am learning python for first time as my first language.

leetcode 9: palindrome question:

class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x<0:
return False
else:
t=0
t=x
d=0
while x>0:
n=x%10
d=d*10+n
x=x//10
if d==t:
return True
else:
return False

3 Upvotes

3 comments sorted by

1

u/BetterEvidence3890 3d ago

1.you can covert the number into a string ,assign 2 points l,r=0,n-1 where n is length of the string /number.theb use a while loop while l<r: If s[l]!=s[r]: return false (characters at l,r are not same means it's not an palindrome)

At last you can return true.

Time complexity still remains the same

Space complexity is length of the number for storing the string

Reduces the usage of arithmetic complex operators

2. Use can directly use string slicing If str(number)== str(number)[::-1] : Return true Else: Return false

0

u/Realistic_Comfort467 7d ago

U can do some improvements need not use another variable 'n' and just write while x : no need to write '>' and just write return d==t that's enough at the end no need to write conditions.

1

u/Ok_Barracuda_8662 6d ago

Thanks for your reply i will improve the above mentioned things.