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.
方法一:从这个整数两端的digit开始,向内判等,如果有不相等的,返回false。具体实现时,首先可以认为负数不是palindromes number,对于0小于10的也可以直接返回true。对于其它数要判断该数的位置,然后比较首尾两端的digit,不等则返回false;相等则比较下一对digit。
代码如下:
bool isPalindrome(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(x < 0) return 0;
if(x >= 0 && x < 10) return 1;
int bit = 1;
int xx = x;
while((xx/=10) > 0) bit++;
while(bit>=2)
{
if((int)(x/pow((double)10,(double)(bit-1))) != x%10) return false;
else{
x -= x/pow((double)10,(double)bit) * pow((double)10,(double)bit);
x/10;
bit-=2;
}
}
return true;
}
方法二:reverse这个integer,然后比较是否相等,关于溢出的问题有影响吗?如果是回文数不会出现溢出,如果不是的话,反转溢出之后恰好和原来的数字相等的可能性。。。所以,可以这样直接做吗?。。。
方法三:分前后两半反转以避免溢出的问题,不觉得是个很妙的方法,懒得实现代码了。
有更简单的写法