題目
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
}