算法题--加1

作者: 岁月如歌2020 | 来源:发表于2020-04-18 17:07 被阅读0次
image.png

0. 链接

题目链接

1. 题目

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.

2. 思路1:最低位加的1和其他位收到的进位可用同一个变量

3. 代码

# coding:utf8
from typing import List


class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        extra = 1
        for i in range(len(digits) - 1, -1, -1):
            digits[i] += extra
            if digits[i] >= 10:
                digits[i] -= 10
                extra = 1
            else:
                extra = 0
                break

        if extra > 0:
            digits.insert(0, 1)

        return digits


solution = Solution()
print(solution.plusOne([1, 2, 3]))
print(solution.plusOne([4, 3, 2, 1]))
print(solution.plusOne([9, 9]))

输出结果

[1, 2, 4]
[4, 3, 2, 2]
[1, 0, 0]

4. 结果

image.png

相关文章

网友评论

    本文标题:算法题--加1

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