题目
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
解题思路
判断是否为回文数
从两端开始比较,先找到最高位和最低位,
最低位,x % 10
最高位,0 < x / 10n < 10 时,x / 10n就是最高位的值, high = 10 n
将最高位和最低位进行比较,然后
x = x % high
x /= 10
high = 10 n-2
去掉最高位和最低位,再进行下一轮比较
注意
x < 0 时都不是回文数
0 < x < 10时都是回文数
代码
func isPalindrome(x int) bool {
fmt.Printf("x:%+v\n", x)
if x < 0 {
return false
} else if x < 10 {
return true
}
//取最高位
high := 10
for x/high > 9 {
high *= 10
}
for x > 0 {
fmt.Printf("new_x:%+v, high:%+v\n", x, high)
numHigh := x / high
numLow := x % 10
fmt.Printf("numHigh:%d, numLow:%d\n", numHigh, numLow)
if numHigh != numLow {
return false
}
x = x % high
x /= 10
high /= 100
}
return true
}