美文网首页程序人生程序员技术干货
LeetCode习题解析-7.ReverseInteger

LeetCode习题解析-7.ReverseInteger

作者: Kindem | 来源:发表于2018-02-24 20:55 被阅读8次

    转自Kindem的博客

    问题

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

    Example 1:

    Input: 123
    Output: 321
    

    Example 2:

    Input: -123
    Output: -321
    

    Example 3:

    Input: 120
    Output: 21
    

    Note:
    Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

    第一次解答

    class Solution:
        def reverse(self, x):
            """
            :type x: int
            :rtype: int
            """
            negative = x < 0
            if negative:
                x = 0 - x
    
            if x % 10 == 0:
                x = x // 10
    
            l = []
            while x:
                l.append(x % 10)
                x = x // 10
    
            number = 0
            count = 0
            for i in l[::-1]:
                number += (10**count) * i
                count += 1
    
            if negative:
                return 0 - number
            else:
                return number
    

    结果给我报错了


    error_picture

    后来突然反应过来,原来将它倒过来之后,也是可能会溢出的,于是改之

    Solution

    class Solution:
        def reverse(self, x):
            """
            :type x: int
            :rtype: int
            """
            negative = x < 0
            if negative:
                x = 0 - x
    
            if x % 10 == 0:
                x = x // 10
    
            l = []
            while x:
                l.append(x % 10)
                x = x // 10
    
            number = 0
            count = 0
            for i in l[::-1]:
                number += (10**count) * i
                count += 1
    
            if number > 2**31 - 1:
                return 0
            else:
                if negative:
                    return 0 - number
                else:
                    return number
    
    

    相关文章

      网友评论

        本文标题:LeetCode习题解析-7.ReverseInteger

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