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

[easy][Array]66.Plus One

作者: 小双2510 | 来源:发表于2017-11-22 23:34 被阅读0次

    原题是:

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

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

    The digits are stored such that the most significant digit is at the head of the list.

    思路是:

    通过Python中Index-1,-2,-3,来从“个位”数,模拟加法的过程。
    逻辑划分是:
    非首位数,分成9和不是9来处理;首位数,分成9和非9来处理。

    代码是:

    class Solution:
        def plusOne(self, digits):
            """
            :type digits: List[int]
            :rtype: List[int]
            """
            i = -1
            while i > - len(digits) :
                if digits[i] < 9 :
                    digits[i] += 1
                    return digits
                elif digits[i] == 9:
                    digits[i] = 0
                i -= 1
                    
            if digits[0] == 9:
                digits[0] = 0
                digits.insert(0,1)
            else:
                digits[0] += 1
            
            return digits
    

    相关文章

      网友评论

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

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