题目
题解
解法一
- 尾+1
尾数当前值(取余)
进位(取整)
- 有进位
下一个数重复上述步骤
当前是最后一个元素
进位插入首元素
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
carry = 1
digits_len = len(digits)
for i in range(digits_len-1, -1, -1):
carry = self.add_num(digits, i, carry)
if carry:
if i == 0:
digits.insert(0, carry)
else:
continue
else:
break
return digits
def add_num(self, digits, index, carry=1):
res = digits[index]+1
carry = res/10
digits[index] = res%10
return carry
解法二
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
carry = 1
digits.insert(0,0)
n = len(digits)-1
while carry > 0:
count= digits[n] + carry
digits[n] = count % 10
carry = count / 10
n -= 1
if digits[0] == 0:
digits.pop(0)
return digits