美文网首页
7. Reverse Integer

7. Reverse Integer

作者: JERORO_ | 来源:发表于2018-05-30 13:57 被阅读0次

    题目描述

    Given a 32-bit signed integer, reverse digits of an integer.

    思路

    凑出符合要求的string,转成int后return

    Detail

    1. 判断正负
    2. 从后往前loop,从第一个非0的数字开始,append到ans中
    3. 如果不为空,且在区间内,返回int(ans)

    Complexity

    Time: O(n)
    Space: O(1)

        def reverse(self, x):
            """
            :type x: int
            :rtype: int
            """
            INT_MAX = 2**31 -1
            INT_MIN = -2**31
            ans = ""
            if x < 0:
                ans += "-"
                x = abs(x)
            string = str(x)[::-1]
            start = False
            for i in string:
                if i != "-" and i != "0":
                    start = True
                if start:
                    ans += i
            if ans == "" or int(ans) > INT_MAX or int(ans) < INT_MIN:
                return 0
            return int(ans)
    

    相关文章

      网友评论

          本文标题:7. Reverse Integer

          本文链接:https://www.haomeiwen.com/subject/voyzjftx.html