[leetCode]Easy — Palindrome Number解題紀錄

Champion Hsieh
Firmware_Engineer
Published in
3 min readJun 21, 2021

Question:

Given an integer x, return true if x is palindrome integer.

An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not.

給一個整數x,如果x是回文整數的話,回傳true。

當一個整數他順向跟反向讀起來是相同的,那它就為回文。

舉裡來說121是回文數,但123不是。

Example 1:

Input: x = 121
Output: true

Example 2:

Input: x = -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: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Example 4:

Input: x = -101
Output: false

Solution:

bool isPalindrome(int x){
if(x<0 || (x>0 && x%10 == 0)) return false;

int compare = 0;
while(x>compare){
compare = compare * 10 + x % 10;
x /= 10;
}
return compare == x || x == compare/10;
}

Note: 先將特例不是回文值的數個別判斷(ex:負數、尾數為0但非單0的數值)

然後利用While迴圈,以一個比較值,每次將該值先乘10加上輸入值取尾數,以呈現回文數值,並將輸入值除以10簡化,而while迴圈中判斷條件為輸入值小於比較值,此時代表輸入值已經至少超過一半進行回文了。

最後利用比較值是否相等於輸入值(輸入值個數為偶數),抑或比較值除以十後是否等於比較值(輸入值個數為奇數)。

--

--