題目
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) return false;
int div = 1;
while (x / div >= 10) div *= 10;
while (x > 0) {
int left = x / div;
int right = x % 10;
if (left != right) return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
};
分析
這道驗(yàn)證回文數(shù)字的題不能使用額外空間,意味著不能把整數(shù)變成字符,然后來驗(yàn)證回文字符串鳄厌。而是直接對整數(shù)進(jìn)行操作养叛,我們可以利用取整和取余來獲得我們想要的數(shù)字椿浓,比如 1221 這個數(shù)字凑兰,如果 計(jì)算 1221 / 1000闹啦, 則可得首位1挠进, 如果 1221 % 10色乾, 則可得到末尾1,進(jìn)行比較领突,然后把中間的22取出繼續(xù)比較暖璧。