题目:
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.
解答:
在提示中提到,如果考虑reverse number的方法,可能造成溢出。
注意到负数不是回文数。
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.
解答:
在提示中提到,如果考虑reverse number的方法,可能造成溢出。
注意到负数不是回文数。
可以考虑每次提取头尾两个数,判断它们是否相等,判断后去掉头尾两个数。
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0)
return false;
if (x < 10)
return true;
int digits = 0;
int t = x;
int d = 0;
while(t != 0) t /= 10, ++d;
int left = pow(10, d - 1);
int right = 1;
while( left >= right)
{
if (x / left % 10 != x / right % 10)
return false;
left /= 10;
right *= 10;
}
return true;
}
};