【Leetcode】判断是否为回文数python实现

方法1:

将 整数转为字符串 ,然后将字符串分割为数组,只需要循环数组的一半长度进行判断对应元素是否相等即可 。

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x<0:
            return False
        else:
            strx = str(x)
            for i in range(len(strx)//2):
                if strx[i]!=strx[len(strx)-1-i]:
                    return False 
            return True

方法2:

 整个数字回转

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x<0 or (x>=10 and x//10==0):
            return False
        else:
            y,res = x,0
            while y != 0 :  
                res = res*10 + y%10
                y //= 10
            return True if res==x else False

 方法3:

通过取整和取余操作获取整数中对应的数字进行比较。

举个例子:1221 这个数字。

通过计算 1221 / 1000, 得首位1
通过计算 1221 % 10, 可得末位 1
进行比较
再将 22 取出来继续比较。

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x<0 or (x>=10 and x//10==0):
            return False
        else:
            dev = 10**(len(str(x))-1)
            while x>0 :
                if x//dev != x%10: return False
                x = x%dev//10
                dev /= 100
            return True

方法4:

 取出后半段数字进行翻转

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x<0 or (x>=10 and x%10==0):
            return False
        else:
            res = 0
            while x > res :  
                res = res*10 + x%10
                x //= 10
            return True if res==x or res//10==x else False

方法5:

由sort中key的用法浅谈python文中看到作者的NB解法!!!!!

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

时间空间占比:

 

 运行时间内存消耗
方法196ms14.7MB
方法2156ms15MB
方法396ms14.9MB
方法492ms14.9MB
方法568ms14.6MB

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值