Table of Content
题目:
这题将数字装换为字符串后比较简单,参考代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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 |
当然,不用str转换也是可以的,通过拆散数字然后借助list进行比较(不要把拆散的数字重构为回文比较,因为数字特别大的时候可能会溢出),注意如果输入的负数可以直接返回FALSE,参考代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
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 |