9. Palindrome Number

判断一个数字是否是回文

不断比较当前数字的首位和末位,如果一样则去除首尾两个数字,继续比较剩下部分的首位和末位,重点在如何得到一个数字的左边和右边的数

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
# 4 star,
if x < 0:
return False
div = 1
while x / div >= 10:
div *= 10
while x > 0:
left = x // div
right = x % 10
if left != right:
return False
x %= div
x //= 10
div //= 100
return True

Go:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func isPalindrome(x int) bool {
if x < 0 {return false}
div := 1
for x / div >= 10 {
div *= 10
}

for x > 0 {
left := x/div
right := x % 10
if left != right {
return false
}
x %= div
x -= right
x /= 10
div /= 100
}
return true
}