Determine whether an integer is a palindrome. Do this without extra space.
click to show spoilers.
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.
思路
回文数类似于 12321,或者 123321。两种思路:
转换数字到字符串后,进行判断
把数字逆序后,看看是否相等,相等就为回文数
解答
package main
import "fmt"
// ----------------------
func isPalindrome(x int) bool {
if x < 0 {
return false
}
xx := x
y := 0
for x != 0 {
y = x%10 + y*10
x = x / 10
}
if y == xx {
return true
} else {
return false
}
}
// ----------------------
func main() {
fmt.Println(isPalindrome(123123123123123))
fmt.Println(isPalindrome(922337203))
fmt.Println(isPalindrome(-123))
fmt.Println(isPalindrome(12521))
fmt.Println(isPalindrome(125521))
}
问题
Determine whether an integer is a palindrome. Do this without extra space.
click to show spoilers.
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.
思路
回文数类似于 12321,或者 123321。两种思路:
解答