【Leetcode-算法-Python3】9. 回文数

1.将整数转为字符串

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        re = False
        s = str(x)
        if s[0] == "-" or s[0] == "+":
            return re
        k = len(s)
        if k == 1:
            return True
        if k == 2:
            if s[0] == s[1]:
                return True
            else:
                return re
        mid = k // 2
        s1 = s2 = ""
        if k % 2 == 0:
            s1 = s[0:mid]
            s2 = s[mid:]
            s2 = s2[::-1]
        else: 
            s1 = s[0:mid]
            s2 = s[mid + 1:]
            s2 = s2[::-1]
        if s1 == s2:
            re = True
        return re

执行用时:412 ms

已经战胜 42.84 % 的 python3 提交记录

2.不将整数转为字符串

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x < 0:
            return False
        if 0 <= x <= 99:
            if 0 <= x <= 9 or x % 11 == 0:
                return True
            else:
                return False
        flag = True
        nums = []
        k = 0
        while x > 0:
            nums.append( x % 10 )
            x = x // 10
            k += 1
        mid = k // 2
        if k % 2 == 0:
            i = mid - 1
            j = mid
        else:
            i = mid - 1
            j = mid + 1
        while i >= 0:
            if nums[i] != nums[j]:
                flag = False
                break
            i -= 1
            j += 1  
        return flag

执行用时:440 ms

已经战胜 23.85 % 的 python3 提交记录

猜你喜欢

转载自blog.csdn.net/aawsdasd/article/details/80785115