[easy][Array]66.Plus One

2017-11-22  本文已影响0人  小双2510

原题是:

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
上一篇下一篇

猜你喜欢

热点阅读