leetcode7:整数反转 python实现

题目

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例 1

输入: 123
输出: 321

示例 2

输入: -123
输出: -321

示例 3

输入: 120
输出: 21

注意

假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

第一次代码

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        LessThanZero = False
        if x < 0:
            LessThanZero = True
            x = abs(x)
        num = []
        flag = True
        while x > 0:
            number = x % 10
            if flag and number == 0:
                x //= 10
                continue
            if number != 0:
                flag = False
            num.append(number)
            x //= 10
        #num.append(x)
        k = len(num) - 1
        aim = 0
        for i in num:
            #print(i)
            aim += i * 10 ** k
            k -= 1
        if LessThanZero:
            aim *= -1
        if (aim >= -2 ** 31) and aim <= (2 ** 31 - 1):
            return aim
        return 0

思路就是不停的取余。第一遍代码使用了列表存放反转的数,其实是很没有必要,这样还得判断0是不是在最高位。结果在取余的循环里直接计算即可。改进后的代码如下,时间还是36ms:
第二次代码

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        LessThanZero = False
        if x < 0:
            LessThanZero = True
            x = abs(x)
        aim = 0
        while x > 0:
            number = x % 10
            aim = aim * 10 + number
            x //= 10
        if LessThanZero:
            aim *= -1
        if (aim >= -2 ** 31) and aim <= (2 ** 31 - 1):
            return aim
        return 0

最后在评论里学到的解法,将数字转换为字符串处理,时间40ms代码如下:

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x < 0:
            x = -int(str(-x)[::-1])
        else:
            x = int(str(x)[::-1])
        if (x >= -2 ** 31) and x <= (2 ** 31 - 1):
            return x
        return 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值