自己写的解:
思路:将数字变成字符串,再逐个字符进行对比
执行用时: 92 ms,超过23%
内存消耗: 14.8 MB,超过20%
class Solution:
def isPalindrome(self, x: int) -> bool:
if x<0:
return False
a = str(x)
length = len(a)-1
if length%2==0:
half_len = int(length/2)
else:
half_len = int(length/2)+1
for i in range(half_len):
if a[i] != a[length-i]:
return False
return True
看了被人思路写的解
执行用时: 72 ms,超过72%
内存消耗: 14.8 MB,超过15%
if x<0:
return False
k = x
X = 0
while(k>0):
X = X*10 + (k%10)
k = k//10
return X == x
最短的解
执行用时: 56 ms,超过99%
内存消耗: 14.9 MB,超过11%
class Solution:
def isPalindrome(self, x: int) -> bool:
return str(x)==str(x)[::-1]
官方提供的解
思路:判断数字的后一半是否和前一半相同,所以只用算一半。
执行用时: 68 ms,超过86%
内存消耗: 14.9 MB,超过7%
class Solution:
def isPalindrome(self, x: int) -> bool:
# 排除负数和能被10除的数
if x<0 or (x%10==0 and x!=0):
return False
revertedNumber = 0
while(x>revertedNumber):
revertedNumber = revertedNumber*10+x%10
x = x//10
# 处理长度为奇数和偶数两种情况
return revertedNumber == x or x==revertedNumber//10