題目描述:
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.
思路:
比較暴力一點的就是轉成string方法,不過這樣很簡單沒什麼意義。如果不用轉換string方法,我們可以先計算這個數字的位數,然後通過取餘并乘上10的位數減1次方。這樣就可以計算出最後的結果。直接上代碼!
代碼:
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0: return False
num = x
check = x
res = 0
c = 0
while x > 0:
x = x // 10
c += 1
while num > 0:
res += (num % 10) * (10**(c-1))
num = num // 10
c -= 1
if res == check:
return True
else:
return False
知識點:
求一個數的位數,一是轉換成string然後用len()求,二就是這種方法。
c = 0 while x > 0: x = x // 10 c += 1