思路
如果单独操作最后一个元素,令其加一,满十进一,会挺麻烦的,要分情况。
所以我的思路是将list还原到字符串,再变成数值,直接+1,然后再还原到list。详见代码
代码
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
s = ""
for i in digits:
s += str(i)
s = int(s) + 1
x = []
for i in str(s):
x.append(int(i))
return x
其他解法
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
length_d = len(digits)-1
while length_d>=0:
if length_d==0:
if digits[length_d]+1>9:
digits[length_d] = 0
result=[1]
result.extend(digits)
return result
if digits[length_d]+1<=9:
digits[length_d] +=1
return digits
else:
digits[length_d]=0
length_d -= 1
return digits