Given two non-negative integers as strings, return their product as a string, without converting the inputs to integers directly or using big-integer libraries.
The product of num1[i] and num2[j] lands in positions i + j and i + j + 1 of an (m + n)-digit result. Add each product into place, push the carry left, then strip leading zeros.
1function multiply(num1: string, num2: string): string {2const m = num1.length, n = num2.length, res = new Array(m + n).fill(0);3for (let i = m - 1; i >= 0; i--)4for (let j = n - 1; j >= 0; j--) {5const sum = +num1[i] * +num2[j] + res[i + j + 1];6res[i + j + 1] = sum % 10;7res[i + j] += Math.floor(sum / 10);8}9const s = res.join("").replace(/^0+/, "");10return s || "0";11}
The product has at most 6 digits.
Space: play/pause · ←/→: step