Determine whether an integer is a palindrome. Do this without extra space.
click to show spoilers.
Some hints:
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.
注意几个问题
1\不使用辅助空间
2\不能翻转数字否则会越界
class Solution {
public:
bool isPalindrome(int x) {
if(x>=0&&x<10)
return true;
int len=0;
int sav=x;
if(x<0)
return false;
while(x)
{
++len;
x/=10;
}
int begin=sav;
int end=sav;
int div=pow(10,len-1);
while(begin)
{
if(begin%10==(end/div)%10)
{
begin/=10;
div/=10;
}
else
return false;
}
return true;
}
};