[LeetCode] 9. Palindrome Number 驗證回文數字


 

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?

 

這道驗證回文數字的題如果將數字轉為字符串,就變成了驗證回文字符串的題,沒啥難度了,我們就直接來做 follow up 吧,不能轉為字符串,而是直接對整數進行操作,可以利用取整和取余來獲得想要的數字,比如 1221 這個數字,如果 計算 1221 / 1000, 則可得首位1, 如果 1221 % 10, 則可得到末尾1,進行比較,然后把中間的 22 取出繼續比較。代碼如下:

 

解法一:

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是否為負數,這里可以用一個小 trick,因為整數的最高位不能是0,所以回文數的最低位也不能為0,數字0除外,所以如果發現某個正數的末尾是0了,也直接返回 false 即可。好,下面來看具體解法,要驗證回文數,那么就需要看前后半段是否對稱,如果把后半段翻轉一下,就看和前半段是否相等就行了。所以做法就是取出后半段數字,進行翻轉,具體做法是,每次通過對 10 取余,取出最低位的數字,然后加到取出數的末尾,就是將 revertNum 乘以 10,再加上這個余數,這樣翻轉也就同時完成了,每取一個最低位數字,x都要自除以 10。這樣當 revertNum 大於等於x的時候循環停止。由於回文數的位數可奇可偶,如果是偶數的話,那么 revertNum 就應該和x相等了;如果是奇數的話,那么最中間的數字就在 revertNum 的最低位上了,除以 10 以后應該和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;
    }
};

 

下面這種解法由熱心網友 zeeng 提供,如果是 palindrome,反轉后仍是原數字,就不可能溢出,只要溢出一定不是 palindrome 返回 false 就行。可以參考 Reverse Integer 這題,直接調用 Reverse()。

 

解法三:

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0 || (x % 10 == 0 && x != 0)) return false;
        return reverse(x) == x;
    }
    int reverse(int x) {
        int res = 0;
        while (x != 0) {
            if (res > INT_MAX / 10) return -1;
            res = res * 10 + x % 10;
            x /= 10;
        }
        return res;
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/9

 

類似題目:

Palindrome Linked List

Reverse Integer

 

參考資料:

https://leetcode.com/problems/palindrome-number/

https://leetcode.com/problems/palindrome-number/discuss/5127/9-line-accepted-Java-code-without-the-need-of-handling-overflow

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM