class Solution: # @return a boolean def isPalindrome(self, x): if x<0: return False flag=1 while x/flag>=10: flag=flag*10 if flag==1: return True else: while flag>=1: x=int((x-(x%10)*flag)/10) flag=flag/100 if x==0: return True else: return False
this piece of code works in this way: 1st use flag to record how many digit this integer have. Then iteratively calculate int((x-(x%10)*flag)/10). If the integer is palindrome, the number of digit will reduce by 2 and finally x would become 0.
However, an additional memory space for flag is used here, though the answer got accepted. Any suggestions on bettering this piece of code would be appreciated.
Thanks for your attention.
def isPalindrome(self, x):
:type x: int
x = str(x)
if x == x[::-1]:
@PunamShaw I did the same way but I am not sure if is considered as a good practice to convert integer to string.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.