題目描述:
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.
題目解析:
代碼如下:
class Solution
{
public:
bool isPalindrome(int x)
{
if(x<0 || x!=0 && x%10==0)
// 如果x是負數或者x是一個10的整數倍的數,那麼x都不可能迴文
return false;
int sum = 0;
int xx = x, num = 0;
while(x > abs(sum) && num++ < 32)
{
// 可以倒着計算出sum,來比對最終的sum和x,從而判斷是否迴文;之所以加上num<32,是因爲防止x爲32位最大整數,此時x永遠大於sum,防止陷入死循環。
sum = sum*10 + xx%10;
xx = xx/10;
}
return (x == sum);
}
};