题目:
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.
Solution(1):
翻转整数,考虑越界即可。
bool isPalindrome(int x)
{
if(x<0)
return false;
int result = 0;
int temp = x;
while(x)
{
if(INT_MAX /10 <= result)
{
if(INT_MAX/10 == result)
{
if(x%10 >= 8)
return false;
}
else
return false;
}
result = result * 10 + x%10;
x/=10;
}
if(temp == result)
return true;
else
return false;
}
Solution(2):
依次比较首尾。代码如下:
bool isPalindrome(int x)
{
if(x<0)
return false;
int base= 1;
while(x / base >= 10)
base *= 10;
while(x)
{
int left_digit = x / base;//左边数字
int right_digit = x%10;
if(left_digit != right_digit)
return false;
x -= left_digit*base;
base /= 100;
x/=10;
}
return true;
}