解法:
需要向面试官问的问题有,可能有负数吗?数字在digits中是如何存储的,正向还是反向?开头会出现0吗?
实现上推荐的方法比我的方法更直接一些。放在循环中的if判断+return比while中的判断更易读。
Python源码:
Runtime: 20 ms, faster than 57.47% of Python online submissions for Plus One.
Memory Usage: 11.9 MB, less than 6.25% of Python online submissions for Plus One.
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
for i in range(len(digits)):
ids = len(digits) - 1 - i
if digits[ids] < 9:
digits[ids] += 1
return digits
else:
digits[ids] = 0
digits.append(0)
digits[0] = 1
return digits
我的心路:
Runtime: 20 ms, faster than 57.45% of Python online submissions for Plus One.
Memory Usage: 11.9 MB, less than 10.42% of Python online submissions for Plus One.
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
i = 1
tmp = 1
while tmp > 0 and i <= len(digits):
tmp = digits[-i] + tmp
digits[-i] = tmp % 10
tmp = tmp // 10
i += 1
if tmp != 0:
digits.insert(0, 1)
return digits