[Math/Array]66. Plus One

2019-02-09  本文已影响0人  野生小熊猫

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!

上一篇下一篇

猜你喜欢

热点阅读