一、直接实现法
1.判断符号
2.取出个位组合成新数
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
res = []
x2 = 0
i = 0
if x < 0:
return False
abs(x)
s=x
while s != 0:
x2 = x2*10+s%10
s //= 10
return x2 == x
以下这种方法很巧妙,其实不用把原数完全反转。只要找到中间的位置就可以
if x < 0 or (x % 10 == 0 and x != 0):
return False
revertedNumber = 0
while(x > revertedNumber):
revertedNumber = revertedNumber * 10 + x % 10
x /= 10
return x == revertedNumber or x == revertedNumber/10
二、字符串法
class Solution(object):
def isPalindrome(self, x):
return str(x) == str(x)[::-1]