判斷整數是否為回文數。不能使用額外空間(即不能轉字符串)。負數不是回文。
div(如 12321 → div=10000)x/div 和最低位 x%10x = (x % div) / 10,div /= 100x == 0class 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; // 位數減 2
}
return true;
}
};
將數字後半段反轉,與前半段比較。需處理奇數位中間數字。
bool isPalindrome(int x) {
if (x < 0 || (x % 10 == 0 && x != 0)) return false;
int reverted = 0;
while (x > reverted) {
reverted = reverted * 10 + x % 10;
x /= 10;
}
return x == reverted || x == reverted / 10;
}
首尾比較法直觀易懂,反轉後半段法更優雅且常數因子更小。面試建議掌握兩種,說明反轉後半段的邊界條件(x%10==0 排除 10, 100 等)。