7. Reverse Integer

发布时间:2019-06-22 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了7. Reverse Integer脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

题目链接Reverse Integer

思路
因为Python中的数字是没有overflow的,即limIT取决于脑的内存。不过题目有额外要求,假设我们只能处理
32-bit signed 的数字区间。 所以需要另外加一个判断。另外,Python内置的int()函数可以把 "001" 转换成数字 1。

数字要注意区分正负。负数反转还是负数。对于Python来说,有两种解法:

  • 可以把数字转换成字符串反转然后转换回数字
  • 可以把反转的数字乘以10加上x % 10,x每次除以10直到0为止

算法复杂度
Pythonic:

时间:O(x)
空间:O(n) where n is the length of x

一般方法:

时间:O(LOGx) 
空间:O(n) where n is the length of x

代码

Pythonic ApPRoach

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

一般方法

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


脚本宝典总结

以上是脚本宝典为你收集整理的7. Reverse Integer全部内容,希望文章能够帮你解决7. Reverse Integer所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。