题目描述
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
想法
- 想法一:把整数转换成字符串然后从中心往两边依次判断
- 想法二:把整数转过来,但是这会有一个问题就是反过来的数可能超过了int的范围
- 想法三:把整数的后半部分转过来,跟前半部分进行比较,那么这里就有一个问题就是如何判断整数已经到了一半,那就是从后面拿数拿出来的数比拿掉后的大了就已经达到了一半
代码
public boolean isPalindrome(int x) {
if(x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int revertedNumber = 0;
while(x > revertedNumber) {
revertedNumber = revertedNumber * 10 + x % 10;
x /= 10;
}
return x == revertedNumber || x == revertedNumber/10;
//可能是奇数也可能偶数
}