Multiply Strings

35 min · multiply()

Two account totals arrive as text because each one may be hundreds of digits long. You need to multiply the digits themselves, not hand the strings to a huge-number parser.

Given two strings num1 and num2 representing non-negative integers, return their product as a decimal string.

Use grade-school multiplication—multiplying digit pairs and carrying place values, as you would on paper. Don't convert either full input to a built-in big-integer type, a type that grows to store integers beyond an ordinary machine integer's range.

A few ground rules:

  • Every character in each input is a decimal digit.
  • Inputs have no leading zeros unless the whole input is "0".
  • If either factor is "0", return "0".
  • A product of lengths m and n needs at most m + n digit slots.

Constraints

  • 1 <= num1.length, num2.length <= 200
  • num1 and num2 contain decimal digits only.
  • Neither input has a leading zero unless it is exactly "0".

Hints

Reserve every possible place

Create an array of num1.length + num2.length zeros. A digit from index i times a digit from index j contributes around positions i + j and i + j + 1.

Accumulate before carrying

Add every digit-pair product into slot i + j + 1. Then walk the result from right to left, leaving value % 10 and carrying value // 10 one slot left.

Normalize the answer

Skip zero slots at the front after all carries are settled. Keep one zero only for the actual zero product.

Follow-up

Can you explain why m + n slots are always enough, even when every digit creates a carry?

Visible cases

Examples

Example 1

ready
Input
num1 = "2"
num2 = "3"
Expected
"6"
Why
one digit pair produces the whole product

Example 2

ready
Input
num1 = "123"
num2 = "456"
Expected
"56088"
Why
the digit-pair products combine through carries

Example 3

ready
Input
num1 = "0"
num2 = "52"
Expected
"0"
Why
a zero factor makes the product zero

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite