您的位置:首页 > 其它

LeetCode#66 Plus One

2015-07-23 21:13 232 查看
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:

def plusOne(digits):
if digits==None or digits==[]:
return digits
index=len(digits)-1
c=1
r=[]
while index>=0 or c==1:
a=digits[index]+c if index>=0 else c
i=a if a<10 else 0
c=a/10
r+=i,
index-=1
return r[::-1]


2) And a faster one:

def plusOne(digits):
if digits==None or digits==[]:
return digits
index=len(digits)-1
while index>=0:
if digits[index]==9:
digits[index]=0
index-=1
else:
#可提前结束
digits[index]+=1
return digits
#走到这,数组里将全是0
digits[0]=1
digits+=1,
return digits
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: