題目
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.
分析
判斷一個整數(shù)是否是回文數(shù)炫贤。首先負數(shù)不是回文數(shù)坠宴。之后判斷前后各個位的數(shù)字是否相同恃泪。
我用的一個數(shù)組去保存各個數(shù)位的數(shù)字。
還可以直接計算其反過來的數(shù)俱尼,但是確保是否溢出。
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;
}