Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

 12 Input: 121 Output: true 

Example 2:

 1234 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:

 123 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?

Related Topics: Math

## 解題邏輯與實作

 1234567891011121314151617181920 class Solution: def isPalindrome(self, x: int) -> bool: if (x < 0) | ((x % 10 == 0 ) & (x != 0)): return False div = 1 while x // div >= 10: div *= 10 while x > 0: highest = x // div lowest = x % 10 if highest != lowest: return False x = (x % div) // 10 div /= 100 return True 

1. 是否為負數，若是負數則不可能是回文
2. 判斷尾數使否為 0，因為最高位數不可為 0 ，因此若尾數為 0 則不可能是回文，當然必須排除掉 0 本身。

 123456789101112131415 class Solution: def isPalindrome(self, x: int) -> bool: if (x < 0) | ((x % 10 == 0 ) & (x != 0)): return False reverse_x = self.reverse(x) return x == reverse_x def reverse(self, x: int) -> int: res = 0; while x != 0: res = res * 10 + x % 10; x //= 10; return res