Determine whether an integer is a palindrome. Do this without extra space.
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.
bool isPalindrome(int x) {
if(x < 0) return 0;
int p = x,q = 1;
while(p / 10){
q *= 10;
p /= 10;
}
while(1){
if(q == 0 || x < 10) break;
if(x % 10 != x / q) return 0;
x %= q;
x /= 10;
q /= 100;
printf("%d %d\n",x,q);
}
return 1;
}
bool isPalindrome(int x) {
if(x < 0) return 0;
int p = x,q = 1;
while(p / 10){
q *= 10;
p /= 10;
}
while(1){
if(q == 0 || x < 10) break;
if(x % 10 != x / q)return 0;
int next = (x / (p / 10)) % 10;
if(!next){
int t
while(!next){
if((x / 10) % 10) return 0;
x /= 10;
next = (x / (p / t)) % 10;
t *= 10;
}
continue;
}
x %= q;
x /= 10;
q /= 100;
printf("%d %d\n",x,q);
}
return 1;
}
看了别人的代码,恍然大悟,只需要把循环的退出条件改为 x == 0 就可以了,不用担心里面存在 0 的情况,如果左边存在若干个 0 ,那么由于 x 的下一次循环的值的位数肯定是小于 p 的,差的位数就是左边 0 的个数,这样的话下次计算出来的首位会保持为 0 ,直至与 p 位数相等,相当于一直拿 0 跟末位比较,最终就是我们想要的结果。
修改之后的代码如下:
bool isPalindrome(int x) {
if(x < 0) return 0;
int p = 1;
while(x / p >= 10) p *= 10;
while(x){
if(x / p != x % 10) return 0;
x = (x % p) / 10;
p /= 100;
}
return 1;
}