天天看点

Python实现"加一"的两种方法

给定一个非空的数值数组代表一个非负整数,对整数进行加一操作

整数最高位存放在数组头位,数组中每一个元素都代表一个数字

你可以认为整数不以0开头,除了数字0以外

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:翻转数组进行加一计算,输出再次翻转后的数组

def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        extra = 0  #进位
        one = 1    #加一
        digits = digits[::-1]
        for index, num in enumerate(digits):
            if num+one+extra == 10:     #判断是否进位
                extra = 1
                one = 0
                digits[index] = 0
            else:     #不进位就直接输出
                digits[index] = num+one+extra
                return digits[::-1]
        digits.append(1)
        return digits[::-1]           

复制

2:数组转整数,加一后再转数组

def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        sum = 0
        for index, num in enumerate(digits):
            sum += num*(10**(len(digits)-index-1))
        sum += 1
        new_list = []
        for i in str(sum):
            new_list.append(int(i))
        return new_list           

复制

算法题来自:https://leetcode-cn.com/problems/plus-one/description/