题目
Determine whether an integer is a palindrome. Do this without extra space.
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.
分析
判断一个整数是否是回文数。首先负数不是回文数。之后判断前后各个位的数字是否相同。
我用的一个数组去保存各个数位的数字。
还可以直接计算其反过来的数,但是确保是否溢出。
bool isPalindrome(int x) {
if(x<0)return false;
int num[20],length=0;
bool answer=true;
while(x>0)
{
num[length]=x%10;
x=x/10;
length++;
}
for(int i=0;i<length/2;i++)
{
if(num[i]!=num[length-1-i])
{
answer=false;
break;
}
}
return answer;
}