美文网首页
[Math/Array]66. Plus One

[Math/Array]66. Plus One

作者: 野生小熊猫 | 来源:发表于2019-02-09 04:43 被阅读0次
    • 分类:Math/Array
    • 时间复杂度: O(n)

    66. Plus One

    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.
    

    代码:

    class Solution:
        def plusOne(self, digits: 'List[int]') -> 'List[int]':
            sum_=1
            n=len(digits)-1
            while(n>=0):
                sum_+=digits[n]
                digits[n]=sum_%10
                sum_=sum_//10
                if sum_==0:
                    return digits
                n-=1
            if sum_!=0:
                digits.insert(0,sum_)
            return digits
    

    讨论:

    1.很简单,早点结束也要设定条件结束!别忘记了!good!

    相关文章

      网友评论

          本文标题:[Math/Array]66. Plus One

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