[leetcode]9. Palindrome Number

简单题,如果不转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

 

posted @ 2019-05-04 18:21  夜歌乘年少  阅读(147)  评论(0编辑  收藏  举报