leetcode题目之数组加1问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36470920/article/details/85011153

先看题目:

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

其实就是说输入一个整型数组,然后将其从左到右转换为整数时,将其整体加个1,然后将加1的数字按照高位到低位,转换成整型数组,然后输出。

我的想法是先将这个原始的数组转换成整型,然后加1,最后再转换成数组。面是我的代码,转换成整型就是先让原始数组倒置,然后依次让倒置后的数组里面的元素乘以1,10,100,...有多少位根据原本的数组大小而定。接下来就是加1运算,最后将最终的结果依次求余数,将余数保存在最后要返回的数组中,最后别忘了逆置,因为那是反着来的。

class Solution:
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        l = digits[::-1]
        sum = 0
        j = 1
        for i in l:
            i *= j
            sum += i
            j *= 10
        # print(sum)
        sum += 1
        re = []
        while(sum != 0):
            m = sum % 10
            re.append(m)
            sum -= m
            sum //= 10
        re = re[::-1]
        print(re)
if __name__ == '__main__':
    S = Solution()
    l = list(input('').split(','))
    l = list(map(int,l))
    print(l)
    S.plusOne(l)

接下来是运行结果:

谢谢观看!

2018.12.15 1:02 am

猜你喜欢

转载自blog.csdn.net/qq_36470920/article/details/85011153