1. 题目
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1: 输入: 121 输出: true
示例 2: 输入: -121 输出: false 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3: 输入: 10 输出: false 解释: 从右向左读, 为 01 。因此它不是一个回文数。
进阶:
你能不将整数转为字符串来解决这个问题吗?
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/palindrome-number 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题思路
不将整数转为字符串的话,一开始是想用数学方法每次求出首位数字和末尾数字,见错误代码。
所以还是老老实实翻转一半数字吧,这样就不会像全部翻转那样可能溢出。这样也要注意处理特殊情况,末尾数字是0的情况。
3. 代码
3.1. 错误代码
class Solution {
public:
int getw(int x){//add by myself, get the width of x
if(x<=0) return 0;
return (int)(log10(x)+1);
}
bool isPalindrome(int x) {
if(x<0) return false;
else if(x<=9) return true;
int front,back;//the first and the last position of x
while(x!=0){
if(getw(x)==1) return true;
back = x%10;
x=x/10;
front = x/((int)pow(10,getw(x)-1));
x=x-front*(int)pow(10,getw(x)-1);
if(back!=front) return false;
}
return true;
}
};
可惜忽略了形如1000021等中间含有0的数字。
3.2. AC代码
class Solution {
public:
bool isPalindrome(int x) {
if(x<0||(x%10==0&&x!=0)) return false;
int res = 0;
while(x>res){
res = 10*res + x%10;
x = x/10;
}
/*
结束循环的时候,
若x==res,则一定是偶数位的回文数;
若x<res,要么是奇数位的回文数,要么就一定不是回文数
*/
return x==res||x==res/10;
}
};