I am trying to retrieve the answer for multiplying two int arrays (output is also an int array).
For example, num1 = [2, 2, 0], num2 = [1, 0] will give us [2, 2, 0, 0]
What I tried was
def multiply(num1, num2):
if num1 == [0] or num2 == [0]:
return [0]
sign = -1 if (num1[0] < 0) ^ (num2[0] < 0) else 1
num1[0] = abs(num1[0])
num2[0] = abs(num2[0])
res = [0] * (len(num1) + len(num2) + 1) # space O(n + m)
for i in range(len(num1) - 1, -1, -1):
for j in range(len(num2) - 1, -1, -1):
res[i + j + 1] += num1[i] * num2[j]
res[i + j] += res[i + j + 1] // 10
res[i + j + 1] %= 10
res[0] *= sign
return res
trying to imitate the grade-school multiplication.
However, in the official answer to this question, it adds these two lines to remove the leading zeros.
res = res[next((i for i, x in enumerate(res) if x != 0), len(res)):] or [0]
return res
I am so confused about how it works. It seems like it is just retrieving the indices of an array where the value is not 0, but I don't understand how next works with that. Also, is there a simpler way to do what it actually tries to do?
[2, 2, 0] * [1, 0]become[2, 2, 0, 0]?