leetcode第7题整数反转

题目描述

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

示例1:

输入: 123
输出: 321python

示例2:

输入: -123
输出: -321函数

示例3:

输入: 120
输出: 21code

注意:
假设咱们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−2^31, 2^31 − 1]。请根据这个假设,若是反转后整数溢出那么就返回 0。htm

解题思路(python)

2^31=2147483648
在看到这个题之后,最容易想到的办法就是使用字符串反转。可是须要进行各类状况的判断,好比大于0小于0;因为python整型没有规定范围,还须要判断2147483648。
yh师兄给我提供了另外一种思路,利用reduce函数进行迭代。我当时没写出来,师兄给了完整的代码以后,我发现这种办法很精巧。我把他的代码也放到这里,感谢他的帮助。教程

#思路一:字符串
class Solution:
    def reverse(self, x):
        """x:int"""
        if (x>2147483647 or x<-2147483648):
            return 0
        if -10 < x < 10:
            return x
        if x>0:           
            x = str(x)
            x = int(str(int(x[::-1])))
            if (x>2147483647 or x<-2147483648):
                return 0
            else:
                return x
        elif x<0:
            x = str(abs(x))
            x=-int(str(int(x[::-1])))
            if (x>2147483647 or x<-2147483648):
                return 0
            else:
                return x

执行用时84ms,内存消耗13.4MB内存

#思路二:reduce函数对字符串迭代处理
from functools import reduce
class Solution:
    def reverse(self, x):
        """x:int"""
        flag = False
        if x > 0:
            flag = True
        else:
            x = -x
        res = reduce(lambda a,b:b+a, [i for i in str(x)])
        res = int(res) if flag else -int(res)
        if res>2147483647 or res<-2147483648:
            return 0
        return res

执行用时88ms,内存消耗13.2MB字符串

reduce函数

Python reduce() 函数,菜鸟教程get

相关文章
相关标签/搜索