841. Multiply two huge integers given as strings
Some values are too big for fixed-width integers, for example exact counters or checksums in low-level code. Interviewers ask you to multiply them digit by digit, the way you would on paper.
Write multiply_strings(a, b). a and b are non-negative integers written as decimal strings with no leading zeros (except the number 0 itself). Return their product as a decimal string with no leading zeros. Do not convert the whole inputs with int(); work digit by digit.
def multiply_strings(a, b)Example 1
Input: multiply_strings('12', '34')
Output: '408'
Example 2
Input: multiply_strings('0', '999')
Output: '0'
Constraints
- 1 <=
len(a),len(b)<= 2,000 - Digits only, no sign
Hint 1
Size the result as len(a) + len(b).
Hint 2
Index i + j + 1 holds the current digit; i + j receives the carry.
Hint 3
Handle '0' early.
Common mistakes
- Calling int() on the whole input, which skips the point of the exercise.
- Leaving leading zeros in the output.
- Returning an empty string for a zero product.
Understand the idea
Grade-school multiplication maps cleanly to an array of digit slots. For '12' x '34': 2 x 4 = 8 goes to slot 3, 2 x 3 = 6 and 1 x 4 = 4 both go to slot 2 (total 10, so slot 2 becomes 0 and slot 1 gets a carry of 1), and 1 x 3 = 3 goes to slot 1, giving 4. The slots read 0, 4, 0, 8, which prints as '408'.