当前位置 : 主页 > 手机开发 > ROM >

[leetcode]9. Palindrome Number

来源:互联网 收集:自由互联 发布时间:2021-06-10
简单题,如果不转string要牺牲一些时间复杂度: Submission Detail 11509 / 11509test cases passed. Status: Accepted Runtime:128 ms Memory Usage:13.2 MB Submitted:1minute ago class Solution: def isPalindrome(self, x: int) - bo

简单题,如果不转string要牺牲一些时间复杂度:

Submission Detail

11509 / 11509 test cases passed. Status: 

Accepted

Runtime: 128 ms Memory Usage: 13.2 MB Submitted: 1 minute ago
class Solution:
    def isPalindrome(self, x: int) -> bool:
        # solve it without converting the integer to a string
        # deal 0
        if x==None:
            return False

        if x < 0:
            return False
        if x == 0:
            return True
        # noraml
        order = []
        while (True):
            remain = x % 10
            div = x // 10
            if div == 0 and remain ==0:
                break
            else:
                order.append(remain)
                x = x // 10

        # is Palindrome
        # notice lengthS >=
        lengthS = len(order)
        if lengthS % 2 == 1:
            # odd
            list1 = order[0:lengthS // 2 + 1]
            list2 = order[lengthS // 2:]
            list2.reverse()
            for index in range(len(list1)):
                if list1[index] == list2[index]:
                    if index == len(list1) -1:
                        return True
                else:
                    # no palindrome
                    return False
        else:
            # even
            list1 = order[0:lengthS // 2]
            list2 = order[lengthS // 2:]
            list2.reverse()
            for index in range(len(list1)):
                if list1[index] == list2[index]:
                    if index == len(list1)-1:
                        return True
                else:
                    # no palindrome
                    return False
上一篇:19.SimLogin_case02
下一篇:Integer to Roman
网友评论