首页 > 其他 > 详细

LeetCode#66 Plus One

时间:2015-07-23 23:18:21      阅读:211      评论:0      收藏:0      [点我收藏+]

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    

 

LeetCode#66 Plus One

原文:http://www.cnblogs.com/acetseng/p/4671800.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!