**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.**
分析:可以发现,负数和10的倍数一定不是回文。此外,有人判断回文直接用两个指针一前一后就能判断,但是该方法并不是最优的,因为我们根本不需要对整数的每一位进行遍历,跟颠倒整数一样,看到回文和颠倒整数,一定要想起取余和除法。
public static boolean isPalindrome(int x) {
if(x < 0 || (x!=0 && x%10 == 0)) {
return false;
}
int sum = 0;
while (x > sum) {
//这里分数字的个数是奇数还是偶数
//如果是奇数,则x < sum,x的数字个数小于sum,这样就在数字中间停止
//如果是偶数,判断是否是回文,是的话,x == sum,则跳出循环,不是则在最后进行以此循环
sum = sum * 10 + x % 10; //sum就是逆序
x = x / 10; //x就是正序
}
return (x == sum) || (x == sum/10);
}