def isPalindrome(x: int) -> bool:
if x < 0 or (x != 0 and x % 10 == 0): # 判断是否x<10
return False
res = 0
while x > res: # 直到中间的时候停止
res = res * 10 + x % 10 # 保存后半部分
x = x // 10 # 消除最后一位
return (x == res // 10) | (x == res) ##判断前后部分是否一致
# 这个方法的复杂度是O(n)
def isPalindrome1(x: int) -> bool:
lst = list(str(x))
while len(lst) > 1:
if lst.pop(0) != lst.pop(): # pop的函数是抹除--pop(0)是开始 pop()是最后一个,在他们被消除前做了一次贡献
return False
return True
# 这个方法的复杂度是O(n^2)
def isPalindrome2(x: int) -> bool:
lst = list(str(x))
a, b = 0, len(lst) - 1
while a <= b:
if lst[a] != lst[b]:
return False
a += 1
b -= 1
return True
# 这个方法的复杂度是O(n)
9. 回文数
最新推荐文章于 2024-07-18 08:26:33 发布