代码实现
解法一:整数转字符串
class Solution:def isPalindrome(self, x: int) -> bool:positive=str(x)inverted=positive[::-1]return positive==inverted
解法二
注意到题目中说,让我们尝试不适用整数转字符串的方法解决这题。
我们可以想到,处理一个数字中各个位置上的值,一般使用%10、/10的方式,所以我们可以想到:
利用 将被/10舍弃的值和剩余的数之间的关系<——>回文数
class Solution:def isPalindrome(self, x: int) -> bool:# 特殊情况的提前排除if x==0:return Trueif x<0 or x%10==0:return False;# 注意分割单位数的情况res=0while x>res:t=x%10res=res*10+tif res==x or x//10==res:return Truex=x//10return False
