leetcode python3 简单题9. Palindrome Number

1.编辑器

我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接

2.第九题

(1)题目
英文:
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

中文:
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses

(2)解法
① 使用str(耗时: 72ms,内存:13.6M)

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x >0 and int(str(x)[::-1]) == x:
            return True
        
        elif x < 0 or int(str(x)[::-1]) != x:
            return False
        
        else:
            return True
# 或者直接用一句话
return str(x) == str(x)[::-1]  # (耗时: 104ms,内存:13.8M)

注意:
1.else中的情况是:x=0或者x < 0 and int(str(x)[::-1]) != x,由于是顺序执行的,所以在elif中就已经将x < 0 and int(str(x)[::-1]) != x的情况给输出为False了,else中只输出x=0为True的情况了

② 直接计算出翻转后的数字(耗时: 88ms,内存:13.7M)

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0:
            return False
        if len(str(x)) >=2:
            shang, yushu = divmod(x, 10)
            if int(str(yushu) + str(shang)[::-1]) == x:
                return True
            else:
                return False
        else:
            return True

注意:
1.这种使用除10的方法只能适用于x的位数大于等于2的情况,如果是一位数,则直接判断是True的了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值