美文网首页
LeetCode 9. Palindrome Number

LeetCode 9. Palindrome Number

作者: 费城的二鹏 | 来源:发表于2018-11-13 16:07 被阅读12次

Palindrome Number

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
判断一个整数是不是回文的

Follow up:
Coud you solve it without converting the integer to a string?
是否可以在不将数字转换成字符串的情况下解决这个问题

代码如下

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        print(x)

        if x < 0:
            print(False)
            return False
        
        if x == 0:
            print(True)
            return True
        
        source = x
        dist = 0
        while source > 0:
            bit = source % 10
            dist = dist * 10 + bit
            source = int(source / 10)

        print(x, dist)
        print(dist == x)
        return dist == x

时间复杂度比较低的写法都是直接使用了字符串反转与比较,这个并不符合 follow 的意思

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        # print(x)

        source = str(x)
        dist = source[::-1]
        print(dist == source)
        return dist == source

相关文章

网友评论

      本文标题:LeetCode 9. Palindrome Number

      本文链接:https://www.haomeiwen.com/subject/zrrlfqtx.html