CodeArchon

mediumMath & GeometryFacebookGoogle

Giant Number Multiplier

A big-integer library multiplies two arbitrarily long decimal strings without using built-in big-number types.

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

Choose approach

123
0
456
1
Mapdigits
0→0
1→0
2→1
3→3
4→6
5→8
1/4
Narrationstep 1 of 4

Processed num1[2] = 3; partial = 001368.

1def multiply(num1, num2):
2 if num1 == '0' or num2 == '0': return '0'
3 m, n = len(num1), len(num2)
4 result = [0] * (m + n)
5 for i in range(m - 1, -1, -1):
6 for j in range(n - 1, -1, -1):
7 mul = int(num1[i]) * int(num2[j])
8 p1, p2 = i + j, i + j + 1
9 s = mul + result[p2]
10 result[p2] = s % 10
11 result[p1] += s // 10
12 return ''.join(map(str, result)).lstrip('0') or '0'
Variables
i=2
partial=001368

How to think about it

  1. Position i+j accumulates carry; i+j+1 holds units.
  2. Strip leading zeros at the end.

Edge cases to catch in interview

  • "0" × anything -> "0".
  • No overflow since digits are base 10.

Examples

Example 1"6"
{"num1":"2","num2":"3","values":["2","3"]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed