1.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.
2.題目要求:驗證回文字符串。
3.方法:利用取整和取余來獲得我們想要的數(shù)字,比如 1221 這個數(shù)字,如果 計算 1221 / 1000, 則可得首位1, 如果 1221 % 10, 則可得到末尾1,進行比較,然后把中間的22取出繼續(xù)比較。
4.代碼:
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;
}
};