【Leetcode_总结】7. 反转整数

O:

给定一个 32 位有符号整数,将整数中的数字进行反转。

示例 1:

输入: 123
输出: 321

 示例 2:

输入: -123
输出: -321

示例 3:

输入: 120
输出: 21

注意:

假设环境只能存储 32 位有符号整数,其数值范围是 [−2^31,  2^31 − 1] 。根据这个假设,如果反转后的整数溢出,则返回 0。


思路:首先题目确定了范围是 [−2^31,  2^31 − 1] 所以超出整数范围的值将会返归0 

首先确定整数大小的范围 min_与max_ 将字符串转换为list之后翻转,翻转的方式可以是 list.reverse() 或者 list[::-1] 正整数翻转之后直接相连,负整数反转后去除末位符号,判断输出是否在所给范围内即可

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        min_ = -pow(2,31)
        max_ = pow(2,31)-1
        if x <= 0:
            l = list(str(x))
            l.reverse()
            b = int('-'+"".join(l).rstrip('-'))
        else:
            l = list(str(x))
            l.reverse()
            b = int("".join(l))
        if b>=min_ and b<= max_:
            return b
        else:
            return 0

 

实际上[::-1]这种方法可以直接使用在字符串上,无需将字符串变成list再做翻转

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        a = abs(x)
        res = int((str(a)[::-1]))
        if x > 0 and res < 2**31-1:
            return res
        if x < 0 and res <= 2**31:
            return -res
        else:
            return 0

 但是并没有提升效率。。。

猜你喜欢

转载自blog.csdn.net/maka_uir/article/details/83239078