問題出處:迴文數
題目描述
判斷一個整數是否是迴文數,當一個整數從前向後讀與從後向前讀相同時,它就是迴文數。
示例1:
Input: 121
Output: true
示例2:
Input: -121
Output: false
說明: 從左到右讀成 -121,從右到左變爲121-。因此它不是迴文數。
示例3:
Input: 10
Output: false
說明: 從右到左爲 01 。因此它不是迴文數。
注意
假設只能存儲 32 位有符號整數,其數值範圍是 [−2^31^, 2^31^ − 1]
。根據這個假設,如果反轉後的整數溢出,則返回 0。
解題思路
- 整數取10的餘數與result*10相加,每次result前進一位,將餘數作爲各位相加,然後x/10,直至x等於0
class Solution:
def reverse(self, x):
return self.get_result(x) if x > 0 else -self.get_result(abs(x))
def get_result(self, x):
result = 0
while x != 0:
result = result * 10 + x % 10
x = int(x / 10)
return result if pow(-2, 31) < result < pow(2, 31) - 1 else 0
- 整數先轉字符串,然後字符串翻轉,再轉回整數
class Solution:
def reverse(self, x):
str_x = str(x)
if str_x[0] == "-":
x = str_x[1:][::-1]
x = -int(x)
else:
x = int(str_x[::-1])
return x if -2147483648 < x < 2147483647 else 0