LeetCode#66 Plus One

Problem Definition:

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

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

Solution:

1) A very traditional thought:

 1 def plusOne(digits):
 2         if digits==None or digits==[]:
 3             return digits
 4         index=len(digits)-1
 5         c=1
 6         r=[]
 7         while index>=0 or c==1:
 8             a=digits[index]+c if index>=0 else c
 9             i=a if a<10 else 0
10             c=a/10
11             r+=i,
12             index-=1
13         return r[::-1]

2) And a faster one:

 1 def plusOne(digits):
 2         if digits==None or digits==[]:
 3             return digits
 4         index=len(digits)-1
 5         while index>=0:
 6             if digits[index]==9:
 7                 digits[index]=0
 8                 index-=1
 9             else:    
10                 #可提前结束
11                 digits[index]+=1
12                 return digits
13         #走到这,数组里将全是0
14         digits[0]=1
15         digits+=1,
16         return digits    
原文地址:https://www.cnblogs.com/acetseng/p/4671800.html