【LeetCode】7. Reverse Integer

32 篇文章 0 订阅
32 篇文章 0 订阅

LeetCode7 传送门

解法:

    应该向面试官提问的问题:负数、结尾为0、溢出。Python的负数取余操作和其他语言不同,需要保存一个符号变量。

我的心路:

    7个月前的解决方法如下,还不错

Runtime: 20 ms, faster than 61.28% of Python online submissions forReverse Integer.

Memory Usage: 11.7 MB, less than 61.29% of Python online submissions for Reverse Integer.

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        
        output = 0
        neg = False
        if (x < 0):
            neg = True
            x = 0 - x
        while(x // 10 != 0):
            output = 10 * output + x % 10
            x = x // 10
        output = 10 * output + x
        if neg:
            output = 0 - output
        if output < -2**31 or output > 2**31 - 1:
            return 0
        return output

    这次的实现,算法简洁性和性能上有了一定程度的提高 

Runtime: 12 ms, faster than 96.63% of Python online submissions for Reverse Integer.

Memory Usage: 11.7 MB, less than 61.29% of Python online submissions for Reverse Integer.

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        sign = 1
        if x < 0:
            sign = -1
            x *= -1
        des = 0
        while x > 0:
            tmp = x % 10
            des = 10 * des + tmp
            x = x // 10
        des *= sign
        if des < -2**31 or des > 2**31-1:
            return 0
        return des

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值