[LeetCode] Palindrome Number


发布于

|

分类

题意

判断给出的一个数字是不是回文数。不能用附加空间。

题解

回文数有没有公式啊啊!!

“Do this without extra space.” 是什么意思…… 也就是说,我得一位一位算么?

注意负数都不是回文数。

第一次尝试

你是 Python,所以可以用一些比较 Python 的思路来做。而且,好像不犯规。

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x < 0:
            return False
        return str(abs(x))[::-1] == str(abs(x))

运行结果

11506 / 11506 test cases passed.
Status: Accepted
Runtime: 312 ms

第二次尝试

上面那个办法仅仅干掉了 27.66% 的人。怎么加速呢?

我发现我多做了两个 abs 是吧,那好,去掉。

代码

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x < 0:
            return False
        return int(str(x)[::-1]) == x

结果

11506 / 11506 test cases passed.
Status: Accepted
Runtime: 280 ms

第三次尝试

恩,去掉无用的东西瞬间减负不少。

最后判断的是两个 int 是不是相等。那么,如果改成判断两个字符串是不是相等呢?

代码

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x < 0:
            return False
        return str(x)[::-1] == str(x)

结果

11506 / 11506 test cases passed.
Status: Accepted
Runtime: 244 ms

Your runtime beats 97.21% of pythonsubmissions.

足够了。

桩程序

if __name__ == '__main__':
    cases = [
        {'x': 123, 'ans': False},
        {'x': 121, 'ans': True},
        {'x': -123, 'ans': False},
        {'x': -121, 'ans': False},
        {'x': 0, 'ans': True},
    ]

    for item in cases:
        ans = (Solution()).isPalindrome(x=item['x'])
        print(str(ans == item['ans']) + "\t=>" + str(ans) + ":" + str(item['ans']))

评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注