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.
使用最基本的方法,将第一个数与倒数第一个数进行比较,如相等,则继续将第二个数与倒数第二个数进行比较,如相等,则进行下一位的比较;
class Solution {
public:
bool isPalindrome(int x) {
int i = 0;
if(x < 0)
return 0;
if(x == 0)
return 1;
int stadin1 = x;
while (stadin1 > 0)
{
stadin1 /= 10;
i++;
}
if (i == 1)
return 1;
int stadin2 = x;
while ((i / 2) > 0)
{
int last = stadin2 % 10;
int tens = 1;
for (int j = i-1; j > 0; j--)
tens = tens * 10;
int first = stadin2 / tens;
if (first != last)
return 0;
stadin2 = (stadin2 - ((first*tens) + last)) / 10;
i -= 2;
}
return 1;
}
};