---
# System prepended metadata

title: 9. Palindrome Number
tags: [LeetCode]

---

---
tags: 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?**

輸入範本如下
```C#
public class Solution {
        public bool IsPalindrome(int x){
        }
}
```


### 直覺想法
1. 因為題目要求不能把數字轉成字串. 所以只能透過餘數運算去取值. 因為要判斷是否為迴文 , 因此倒過來取值 , 若此此數字與原來的數字相同 , 則此數字是回文.
    ```C#
    60 ms	15.9 MB	
    You are here!
    Your runtime beats 84.28 % of csharp submissions

    public bool IsPalindrome(int x)
    {
        if (x < 0) { return false; }

        long reverse = 0, temp = x;
        while (temp != 0)
        {
            reverse = reverse * 10 + (temp % 10); // 結果可能會超過 int.MaxValue , 所以使用 long
            temp /= 10;
        }
        return reverse == x;
    }
    ```
    
2. 每次取出最左以及最右的數字比較 , 若不同 , 此數字非回文 , 若相同 , 則繼續比較.
```C#
56 ms	15.8 MB
You are here!
Your runtime beats 93.52 % of csharp submissions.
public bool IsPalindrome(int x)
    {
        if (x < 0) { return false; }

        int div;
        for (div = 1; (x / div) >= 10; div *= 10) ; // 找到 x 的位數 , 若 x 為個位數 , div 不應該 *10
        while (x > 0)
        {
            int left = x / div, right = x % 10;
            if (left != right) { return false; }

            x = (x % div) / 10; // 取出除了左與右外的數字.
            div /= 100;         // 因為少了兩個位數 , 所以 div 要除 100
        }
        return true;
    }
```








### Thank you! 

You can find me on

- [GitHub](https://github.com/s0920832252)
- [Facebook](https://www.facebook.com/fourtune.chen)

若有謬誤 , 煩請告知 , 新手發帖請多包涵

# :100: :muscle: :tada: :sheep: 
