Simulate long addition process. Remember to handle the last carry when it is greater than zero.
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
result = [0] * (len(digits) + 1)
i = len(digits) - 1
j = i + 1
carry = 1
while i >= 0 or carry > 0:
if i >= 0:
result[j] = (digits[i] + carry) % 10
carry = (digits[i] + carry) // 10
i -= 1
j -= 1
else:
result[j] = carry
j -= 1
carry = 0
return result if j == -1 else result[j+1:]
No comments:
Post a Comment