力扣-9-回文数

9. 回文数 - 力扣(LeetCode)

学到的

  • 双指针遍历字符串
  • Python反转字符串的快捷写法
  • 纯数论遍历与反转整型数字
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class Solution:
"""
类似双指针
左右以此对比
直到右指针索引比左指针小
"""
def isPalindrome1(self, x: int) -> bool:
s = str(x)
print(s)
i , j = 0, len(s) - 1
while i <= j:
if s[i] != s[j]: return False
i += 1
j -= 1
return True

"""
Python中直接反转字符串
"""
def isPalindrome2(self, x: int) -> bool:
# 从头到尾,步长-1
return str(x) == str(x)[::-1]

"""
纯数学解法
1.掌握遍历 int 类型,即先x mod 10,再x / 10,直至 x = 0
2.反转整数,rev初始等于0,rev = rev*10 + x mod 10
"""
def isPalindrome3(self, x: int) -> bool:
# 负数肯定不是
if x < 0: return False
# 0~9 都是
elif x < 10: return True
else:
# 末尾为0 肯定也不是
if x % 10 == 0: return False
else:
rev = 0
while x != 0:
# 逐个反转
rev = rev * 10 + x % 10
# 除法取整数
x //= 10
# 奇数位数的回文数
if rev == x // 10: return True
# 偶数位数的回文数
if rev == x: return True
return False

"""
对 isPalindrome3 的优化
"""
def isPalindrome4(self, x: int) -> bool:
# 负数、正数且尾数为 0 的不是
if x < 0 or x > 0 and x % 10 == 0: return False
rev = 0
# 当前已反转的 小于 当前再去一次尾数的
# 奇数位时: 121, 1 = 12 // 10, 退出循环,满足 rev == x // 10
# 特别地, 各位数时:8, 8 > 8 // 10, 退出循环,满足 rev == x // 10
# 偶数位时:1221, 12 > 12 // 10, 退出循环,满足 rev == x
# 若不是回文数: 则都不满足
while rev < x // 10:
rev = rev * 10 + x % 10
x //= 10
return rev == x or rev == x // 10

力扣-9-回文数
https://blog.gutaicheng.top/2025/08/25/力扣-9-回文数/
作者
GuTaicheng
发布于
2025年8月25日
许可协议