C++實現(xiàn)LeetCode(9.驗證回文數(shù)字)
[LeetCode] 9. Palindrome Number 驗證回文數(shù)字
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
這道驗證回文數(shù)字的題如果將數(shù)字轉(zhuǎn)為字符串,就變成了驗證回文字符串的題,沒啥難度了,我們就直接來做 follow up 吧,不能轉(zhuǎn)為字符串,而是直接對整數(shù)進行操作,可以利用取整和取余來獲得想要的數(shù)字,比如 1221 這個數(shù)字,如果 計算 1221 / 1000, 則可得首位1, 如果 1221 % 10, 則可得到末尾1,進行比較,然后把中間的 22 取出繼續(xù)比較。代碼如下:
解法一:
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;
}
};
再來看一種很巧妙的解法,還是首先判斷x是否為負數(shù),這里可以用一個小 trick,因為整數(shù)的最高位不能是0,所以回文數(shù)的最低位也不能為0,數(shù)字0除外,所以如果發(fā)現(xiàn)某個正數(shù)的末尾是0了,也直接返回 false 即可。好,下面來看具體解法,要驗證回文數(shù),那么就需要看前后半段是否對稱,如果把后半段翻轉(zhuǎn)一下,就看和前半段是否相等就行了。所以做法就是取出后半段數(shù)字,進行翻轉(zhuǎn),具體做法是,每次通過對 10 取余,取出最低位的數(shù)字,然后加到取出數(shù)的末尾,就是將 revertNum 乘以 10,再加上這個余數(shù),這樣翻轉(zhuǎn)也就同時完成了,每取一個最低位數(shù)字,x都要自除以 10。這樣當 revertNum 大于等于x的時候循環(huán)停止。由于回文數(shù)的位數(shù)可奇可偶,如果是偶數(shù)的話,那么 revertNum 就應(yīng)該和x相等了;如果是奇數(shù)的話,那么最中間的數(shù)字就在 revertNum 的最低位上了,除以 10 以后應(yīng)該和x是相等的,參見代碼如下:
解法二:
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0 || (x % 10 == 0 && x != 0)) return false;
int revertNum = 0;
while (x > revertNum) {
revertNum = revertNum * 10 + x % 10;
x /= 10;
}
return x == revertNum || x == revertNum / 10;
}
};
到此這篇關(guān)于C++實現(xiàn)LeetCode(9.驗證回文數(shù)字)的文章就介紹到這了,更多相關(guān)C++實現(xiàn)驗證回文數(shù)字內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

