虽然题目简单,但有一个进阶的提问;能不用字符串将这个问题解答出来?

class Solution:
def isPalindrome(self, x: int) -> bool:
xls = list(str(x))
if xls ==xls [::-1]:
return True
else:
return False
pass:Python可以用表达式写,非常简短以及优美
class Solution:
def isPalindrome(self, x: int) -> bool:
return True if str(x) == str(x)[::-1] else False
return str(x) == str(x)[::-1]
更加简短的,这个 == 本身就包含了True and False


if x<0:
return False
ans = 0
old = x
while x>0:
tmp = x%10
ans = ans*10 + tmp
x //= 10
return ans==old
进阶:优化 
不行的情况 
if x<0 or (x%10==0 and x!=0):
return False
ans = 0
while x > ans:
ans = ans*10 + x%10
x //= 10
return x==ans or x==(ans//10)
进阶题解链接
|