題目
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.
解題思路:
這道題首先要理解什么是回文數字,就是從左到右的數字順序和從右到左的數字順序是一樣的,比如 12321。判斷一個數字是否是回文數字有以下規則
- 負數不是回文數字。
- 能被 10 整除的也不是負數,0 除外。
- 若是數字的位數是偶數位 n,那么從右向左反轉 n/2 位數字,然后和剩下的 n/2 位從左向右數字比較,若是相等則是回文數字。 如
12344321 可以拆解成 1234 和 1234 對比。 - 若是數字的位數是奇數位 n+1 ,那么從右向左反轉 n/2 + 1 位數字得到數字 m,再將 m / 10 去掉個位數的到 q ,然后和剩下的 n/2 位從左向右數字比較,若是相等則是回文數字。如 12321,可以拆解成 12 和 12 對比。
解題代碼:
class Solution {
public:
bool isPalindrome(int x) {
// 去掉負數和能夠被 10 整除的數,0 除外
if(x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
// 反轉數字
int revertedNumber = 0;
while(x > revertedNumber) {
revertedNumber = revertedNumber * 10 + x % 10;
x /= 10;
}
return x == revertedNumber || x == revertedNumber/10;
}
};