題目:
題目
這題將數(shù)字裝換為字符串后比較簡(jiǎn)單涨颜,參考代碼如下:
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
int_r = x
str_r = str(int_r)
if str_r == str_r[::-1]:
return True
else:
return False
當(dāng)然,不用str轉(zhuǎn)換也是可以的蟆肆,通過(guò)拆散數(shù)字然后借助list進(jìn)行比較(不要把拆散的數(shù)字重構(gòu)為回文比較拴竹,因?yàn)閿?shù)字特別大的時(shí)候可能會(huì)溢出),注意如果輸入的負(fù)數(shù)可以直接返回FALSE箱歧,參考代碼如下:
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
int_r = x
str_r = str(int_r)
if str_r == str_r[::-1]:
return True
else:
return False
def isPalindrome2(self, x):
"""
:type x: int
:rtype: bool
"""
int_r = x
if int_r < 0:
return False
list_t = []
while int_r:
list_t.append(int_r % 10)
int_r = int_r // 10
if list_t == list_t[::-1]:
return True
else:
return False
ps:如果您有好的建議矾飞,歡迎交流 :-D,也歡迎訪問(wèn)我的個(gè)人博客:tundrazone.com