基础算法之整数翻转(Leetcode-7)

春招第一步,算法伴我行

计划着每天研究几道算法题,各个类型尽可能都包含,自己写出来,好做增强。基本都使用python语言编写,主要讲一下自己的思路,以及AC情况。水平不够,大家多指正,不吝赐教,十分感谢。

题目描述:

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。(简单)
如:123 — 321;-123 — -321;120 —21
同时,只能存储32位有符号整数,范围为[-2^31, 2^31-1],翻转后溢出返回0.

思路:

对于输入的数,无非两种情况:正数和负数。
正(负)数:返回的结果也是正(负)数,sign = 1 if x>0 else -1
然后就是对输入的数字分别提取每一位再进行拼接得到最后的输出结果,当然,前提是先将输入变为正数。

x = abs(x)
current = []
while x>0:
	current.append(x%10)
	x = x//10
result = int(''.join(current))
return sign*result if (result>=MinNum and result<=MaxNum) else 0

完整代码如下:

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x == 0: return 0
        MaxNum = 2**31-1
        MinNum = -2**31
        sign = 1 if x > 0 else -1
        x = abs(x)
        current = []
        while x>0:
            current.append(str(x%10))
            x = x//10
        result = int(''.join(current))
        return result*sign if (result<MaxNum and result>MinNum) else 0

AC

猜你喜欢

转载自blog.csdn.net/weixin_28872169/article/details/86063948