码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode#66 Plus One

时间:2015-07-23 23:19:21      阅读:130      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!