思路一:转换成字符串再转换成列表
class Solution:
def isPalindrome(self, x: int) -> bool:
s=list(str(x))
for i in range(len(s)//2):
if i=="-":
return False
if s[0]!=s[-1]:
return False
s.pop(0)
s.pop(-1)
return True
转换成字符串浪费空间
思路二:常规反转数字,为避免反转溢出,可以只反转后半段
class Solution:
def isPalindrome(self, x: int) -> bool:
if x<0 or (x%10==0 and x!=0):
return False
#转换后半部分,与前半部分比较
revert=0
while x>revert:
revert=revert*10+x%10
x//=10
# 当数字长度为奇数时,我们可以通过 revert/10 去除处于中位的数字。
#例如,当输入为 12321 时,在 while 循环的末尾
#我们可以得到 x = 12,revert = 123,
return x==revert or x==revert//10