# 9. Palindrome Number <span class='tag' data-diff='easy'></span>
{%hackmd RN5D4nggQRO8wzNqxuvlNw %}
## 題目
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?
## 思路
由於這題也是簡單難度,所以想要試者挑戰一下不同的解法--不轉換成字串。首先想到是要用迴圈依序比較最高位與最低位數字,所以需要先知道總共有幾位,可以用取 $log_{10}$ 來得到,接下來就簡單了,最高位只要除以 $10^k$ 而最低位只要對 $10$ 取餘數即可得到,之後再將最高位與最低位移除,進到下一個iteration。若比較過程中有出現不一樣,立即回傳`false`,若全部比較完沒有不同,則回傳`true`。
```javascript
let digits = Math.floor(Math.log10(x));
do{
if((x%10) !== Math.floor(x / 10**digits)) return false;
x = Math.floor((x%(10**digits)) / 10);
digits -= 2;
} while(digits > 0);
return true;
```
由於負數前面有負號,一定不會是回文數字,再者,個位數僅有一位數字,必為回文,所以在一開始即可先判斷這些例外。