Multiply two huge numbers stored as strings, like on paper: each digit pair lands at position i + j + 1, then carry the overflow leftward.
▼The problem
LeetCode 43 (Medium). Given two non-negative integers num1 and num2 as strings, return their product, also as a string, without converting the inputs to integers directly and without a big-integer library. Up to 200 digits each, no leading zeros except the number 0 itself.
Examples: "2" × "3" → "6" and "123" × "456" → "56088" (LeetCode's); "0" × "52" → "0" (the slots read "000"; the answer is a single zero).
The solution
def multiply(num1, num2):
m, n = len(num1), len(num2)
pos = [0] * (m + n)
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
mul = int(num1[i]) * int(num2[j])
total = mul + pos[i + j + 1]
pos[i + j + 1] = total % 10
pos[i + j] += total // 10
out = ''.join(map(str, pos)).lstrip('0')
return out or '0'Transcript
Multiply Strings. You get two non-negative numbers as strings of digits. Return their product, also as a string. No converting them to integers, and no big number library.
Two times three is six. One twenty-three times four fifty-six is fifty-six thousand and eighty-eight. Zero times fifty-two is just zero, not a row of zeros.
The obvious move: convert, multiply, convert back. That's exactly what's forbidden, and two hundred digits would overflow a sixty-four bit integer, which tops out at nineteen.
So multiply the way you learned in school, digit by digit. A number with m digits times one with n digits has at most m plus n digits, so lay out m plus n slots, all zero. Here's the trick: digit i times digit j always lands in slot i plus j plus one. Each slot keeps one digit, and the tens carry one slot left, into slot i plus j.
Let's run one twenty-three times four fifty-six, from the right. Three times six is eighteen: keep eight, carry one. Three times five is fifteen, plus one is sixteen. Three times four is twelve, plus one, thirteen. The two row lands one slot further left: twelve, ten and eight, each added to what's there. The one row: six, five, four. The slots read zero, five, six, zero, eight, eight. Drop the leading zero: fifty-six thousand and eighty-eight.
In code, make m plus n zeros, and loop over both strings from the right. Multiply the two digits, and add what's already in slot i plus j plus one. Keep the last digit there; add the tens to slot i plus j. Finally, join the slots, strip the leading zeros, and return zero if nothing is left.
Every digit pair meets exactly once, so the time is order m times n. The only extra memory is the slots: order m plus n space.
Multiply each pair, drop it in slot i plus j plus one, and carry the tens left. That's Multiply Strings.