【LeetCode】7. Reverse Integer

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

 


版权声明:本文为weixin_42344158原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。