给定一个由 整数 组成的 非空 数组所表示的非负整数,在该数的基础上加一。(老规矩第一个是我写的,后面的两个我从执行时间和消耗内存最少个抄了一个)
class Solution(object):
def plusOne1(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
if digits[0] == 0:
digits[-1] += 1
return digits
int_str = ""
for item in digits:
int_str += str(item)
ret_str = str(int(int_str) + 1)
return [int(item) for item in ret_str]
def plusOne2(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
newlst = []
while digits and digits[-1] == 9:
digits.pop()
newlst.append(0)
if not digits:
return [1] + newlst
else:
digits[-1] += 1
return digits + newlst
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits[-1] = digits[-1] + 1
time_num = 0
res_num = []
for i in range(len(digits), 0, -1):
num = (time_num + digits[i-1]) # 这里是关键
if num > 9:
res_num.append(0)
time_num = 1
else:
res_num.append(num)
time_num = 0
if time_num:
res_num.append(time_num)
res_num.reverse()
return res_num
if __name__ == '__main__':
s1 = Solution()
digits = [4, 3, 2, 1]
digits = [1, 9, 9, 9]
print(s1.plusOne(digits))