题目 #
Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
- For example, 121 is a palindrome while 123 is not.
思路1 #
- 最简单直接的想法,转成字符串,然后判断
1func isPalindrome(x int) bool {
2 s := fmt.Sprint(x)
3 i := 0
4 j := len(s) - 1
5 for i < j {
6 if s[i] != s[j] {
7 return false
8 }
9 i++
10 j--
11 }
12 return true
13}
思路2 #
- 无情打脸,官方解法nb
- 转字符串太占内存,直接反转一半(位数为奇数多反转一个)的数字,然后比较
位数为奇数
@startuml
rectangle x {
(121) as left1
(12) as left2
(1) as left3
}
rectangle revert {
( ) as right1
(1) as right2
(12) as right3
}
(x == revert/10) as mid
left1 --> left2
left2 --> left3
right1 --> right2
right2 --> right3
left3 --> mid
right3 --> mid
@enduml
位数为偶数
@startuml
rectangle x {
(1221) as left1
(122) as left2
(12) as left3
}
rectangle revert {
( ) as right1
(1) as right2
(12) as right3
}
(x == revert) as mid
left1 --> left2
left2 --> left3
right1 --> right2
right2 --> right3
left3 --> mid
right3 --> mid
@enduml
代码实现
1func isPalindrome(x int) bool {
2 if x == 0 {
3 return true
4 }
5 if x < 0 || x%10 == 0 {
6 return false
7 }
8 revertNum := 0
9 for x > revertNum {
10 revertNum = revertNum*10 + x%10
11 x /= 10
12 }
13 return x == revertNum || x == revertNum/10
14}