LeetCode 9. Palindrome Number

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容