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.
代码:
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
i=len(digits)-1
while i>=0:
if(digits[i]!=9):
digits[i]+=1
break
else:
digits[i]=0
i-=1
if i==-1:
digits.insert(0,1)
return digits
该题是将列表转化成数字,再加一,再转成列表。该题有两种做法,第一种如同题意,先将列表转化成数字,再将数字转化成列表。第二种方法是从列表的最后一位开始,判断是否为9,如果是9则变为0,直至不为9,若一直为9则在列表首部加入数字1。我采用的是第二种方法。