KatInterview

Multiply Large Numbers as Strings

StringsAuto-graded · 22 test cases
MediumAuto-gradedStringsmathsimulationarray-manipulation

Last updated

Tests implementation of grade-school multiplication on arbitrarily large integers represented as strings without using built-in big integer operations.

Write a function that computes the product of two non-negative integers given as strings. You must not convert the strings to integers using built-in parsing or use any big integer libraries.

Your function should accept two string parameters, each representing a non-negative integer, and return their product as a string.

Constraints

  • Each input string has length between 1 and 200
  • Input strings contain only digits ('0'-'9')
  • Input strings do not have leading zeros except for the number zero itself ("0")
  • You may not use int(), eval(), or any built-in arbitrary-precision arithmetic

Examples

Example 1

Input: multiply_strings('123', '456')

Output: '56088'

Example 2

Input: multiply_strings('2', '3')

Output: '6'

Example 3

Input: multiply_strings('0', '999')

Output: '0'

Example 4

Input: multiply_strings('99999999999999999999', '1')

Output: '99999999999999999999'

Hints

Hint 1

Consider how you would multiply two numbers by hand on paper, digit by digit, carrying as you go.

Hint 2

A product of an m-digit number and an n-digit number has at most m+n digits. You can allocate an array of that size to hold intermediate results.

Hint 3

When multiplying digit at position i in the first number by digit at position j in the second number, the contribution lands at a specific position in the result array. Think about which position that is.