Add to Array-Form of Integer
franklinqin0 Array
# Solution
# Schoolbook Addition
Add K
to last element in A
, do bitwise addition, then handle the carry.
Complexity
time:
space:
where n
is length of A
.
def addToArrayForm(self, A: List[int], K: int) -> List[int]:
A[-1] += K
for i in reversed(range(len(A))):
carry, A[i] = divmod(A[i], 10)
if i: A[i-1] += carry
if carry:
# OR list comprehension: A = [int(i) for i in str(carry)] + A
A = list(map(int, str(carry))) + A
return A
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9