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; } };
類似題目:
參考資料:
https://leetcode.com/problems/palindrome-number/solution/