这题简单,但是有两个陷阱
1) 负数都不是回文数,所以全部返回false。如果定义负数也可以是回文数的话,那么要注意-2147483648的情况单独处理,因为不能直接变成-x,否则越界。
const int MIN_INT = -2147483648;
const int MAX_INT = 2147483647;
2) pow(x,y)里面的x,y都是double,所以会导致pow(10,5)=9999(因为有取整),而不是10000。解决办法有两个:
方法1:
const int num=10;
然后把num放到pow()的第1个参数里。
方法2:参考https://stackoverflow.com/questions/9704195/why-pow10-5-9-999-in-c
Replace floating point unit (FPU) having higher calculation precision in double
type. For example, we use SSE in Windows CPU. In Code::Block 13.12, we can do this steps to reach the goal: Setting -> Compiler setting -> GNU GCC Compile -> Other options, add
-mfpmath=sse -msse3
The picture is as follows:
add <code>-mfpmath=sse -msse3</code> http://aleeee.qiniudn.com/change%20SSE%20in%20CB.png
bool isPalindrome(int x) {
if (x<0) return false;
int x1=x;
int len=0;
const int num=10;
while(x1) {
x1=x1/10;
len++;
}
while(x>0) {
int powV=pow(num, len-1);
int last_digit = x%10;
int begin_digit = x/powV;
if (last_digit == begin_digit) {
x=x%powV;
x=x/10;
}else{
return false;
}
len-=2;
}
return true;
}
方法2:Leetcode网上公布的这个解法我觉得很不错。
要注意的地方有2点:
1) while(x>revertedNumber) 这里的循环进行到差不多一半就可以停了,然后看revertedNumber和x是否相等(x为偶数个数字),或x==revertedNumber/10(x为奇数个数字)。
2) 条件(x%10==0 && x!=0) 是针对x以0结尾的情况。因为x=10的时候x和revertedNumber最后都会变成0,虽然相等但x不是回文数。x=220时,x和revertedNumber最后都是2。x也不能算回文。
bool isPalindrome2(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;
}