leetcode9. 回文数

https://leetcode-cn.com/problems/palindrome-number
有一个星期没做题了,拿个简单的练下手。
看到题目第一个想法就是reversed([]):

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        list_x = list(str(x))
        if list_x == list(reversed(list_x)):
            return True
        else:
            return False

执行用时:556 ms,非常慢!

那就不用额外空间,只比较一半的数:

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x < 0 or (x % 10 == 0 and x !=0):
            return False
        half_num = 0
        while x > half_num:  # x有len(str(x))//2的长度
            half_num = half_num * 10 + x % 10
            x = x // 10
        return x == half_num or x == half_num // 10

执行用时: 644 ms,更慢了,可能是因为有乘法计算。

看了下更简单的Python解法:

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

额~Python大法好!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值