Likou brushing notes: 66. Add one (save the result in the queue, judge the carry character, detailed notes, the speed exceeds 94%)

topic:

66, plus one

Given a non-negative integer represented by a non-empty array of integers, add one to the number.

The highest digit is stored in the first position of the array, and each element in the array only stores a single number.

You can assume that in addition to the integer 0, this integer does not start with a zero.

Example 1:

Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The input array represents the number 123.

Example 2:

Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The input array represents the number 4321.

Example 3:

Input: digits = [0]
Output: [1]

prompt:

1 <= digits.length <= 100
0 <= digits[i] <= 9

Problem solution ideas:

Use the queue to store the result array, traverse the array in reverse order, determine the locator, see the code comments for details.

Problem solution python code:

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        queue = collections.deque()
        digits[-1] += 1   # 加一
        flag = 0   # 定义进位符
        for i in range(len(digits)-1, -1, -1):  # 倒叙遍历
            digits[i] += flag  # 更新进位
            flag = 0   # 重置进位
            if digits[i]>9:   # 判断是否需要进位,进位就在队列中添加减去10后的余数,同时将进位符置1
                queue.appendleft(digits[i]-10)
                flag = 1
            else: queue.appendleft(digits[i])  # 不需要进位,则在队列左边添加之前的数
        if flag: queue.appendleft(1)    # 最后判断最高位有无进位
        return list(queue)

Insert picture description here

Author: a-qing-ge
links: https://leetcode-cn.com/problems/plus-one/solution/dui-lie-pan-duan-jin-wei-fu-xiang-xi-zhu-hm7g/
sources : LeetCode https://leetcode-cn.com/problems/plus-one/

Guess you like

Origin blog.csdn.net/weixin_44414948/article/details/114413480