[
array
math
]
Leetcode 0989. Add to Array-Form of Integer
Problem statement
https://leetcode.com/problems/add-strings/
Solution
Very similar to Leetcode 0415. Add Strings, use schoolbook sum.
Complexity
It is O(n)
, where n
is the length of num1
.
Code
class Solution:
def addToArrayForm(self, num1, k):
num2 = str(k)
l1, l2, carry, ans = len(num1) - 1, len(num2) - 1, 0, []
while l1 >= 0 or l2 >= 0 or carry:
d1 = int(num1[l1]) if l1 >= 0 else 0
d2 = int(num2[l2]) if l2 >= 0 else 0
carry, digit = divmod(d1 + d2 + carry, 10)
ans += [str(digit)]
l1, l2 = l1 - 1, l2 - 1
return ans[::-1]