LEETCODE 02

LEETCODE 02

7 整数反转

整数反转
解法一:字符串截取

a[开始截取位置:结束截取位置:步长] 包括开始截取位置字符,不包括结束截取位置字符。步长-1则代表反向截取。例如 a = [1, 2,
3, 4, 5, 6, 7] ,求a[1:5:-2],因为步长为-2,是负数,先对a反转,即[7, 6, 5, 4, 3, 2,
1],然后对反转后的列表从index=1(值为6)开始进行切片,结束位置index=5 (值为2), 步长为2,即[6, 4, 2]。

class Solution:
    def reverse(self, x: int) -> int:
        str_x=str(x)
        if str_x[0]!='-':
            res=int(str_x[::-1])
        else:
            temp=int(str_x[::-1][:-1])
            res=-temp
        return res if -2147483648 < res < 2147483647 else 0

解法二:

def reverse_better(self, x: int) -> int:
        y, res = abs(x), 0
        # 则其数值范围为 [−2^31,  2^31 − 1]
        boundry = (1<<31) -1 if x>0 else 1<<31
        while y != 0:
            res = res*10 +y%10
            if res > boundry :
                return 0
            y //=10
        return res if x >0 else -res

9 回文数

回文数

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

            return True if res==x else False

优化

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

            return True if res==x else False
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值