Leetcode第三题——回文数

题目:
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
直接用字符串切片:

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

看到其他大佬写的非常漂亮的同思想代码为:

class Solution:
    def isPalindrome(self, x: int) -> bool:
        s = str(x)
        return s == s[::-1]

作者:jue-qiang-zha-zha
链接:https://leetcode-cn.com/problems/palindrome-number/solution/hui-wen-shu-by-jue-qiang-zha-zha/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

进阶版:不转换为字符串进行判断,我没想出来,后来看大佬的是用数学思想解决,这里附上代码:

class Solution:
    def isPalindrome(self, x: int) -> bool:
        # 不用字符串,则用数学思想解
        if x < 0 or (x % 10 == 0 and x !=0 ):
            return False
        rem = 0
        while x > rem:
            rem = rem*10 + x%10
            x = x//10
        return x == rem or x == rem//10

作者:jue-qiang-zha-zha
链接:https://leetcode-cn.com/problems/palindrome-number/solution/hui-wen-shu-by-jue-qiang-zha-zha/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值