Multiply Strings
Multiply two numbers of any length, given as strings of digits, the way long multiplication works on paper.
Given two non-negative integers num1num2BigInteger
Example 1
Output: "6"
Example 2
Output: "56088"
The Idea
You have multiplied 123 by 456 on paper at school. You write 123 × 6, then 123 × 5 shifted one place to the left, then 123 × 4 shifted two places, and add the three rows. Every multiplication along the way uses only two single digits, so the method works for numbers of any length.
Why not read the strings into a longlonglong
The shifted rows raise a question, though. In 123, the 2 means 20, and in 456, the 5 means 50. Their product, 2 × 5 = 10, really means 1,000, which is 10 hundreds. So where a digit product belongs depends only on where its two digits sit. Can we drop it straight into the right column, without writing out the rows?
First, how many columns does the answer need? A three-digit number is below 1,000, so 123 × 456 is below 1,000 × 1,000 = 1,000,000, the smallest seven-digit number. So the product has at most six digits. Give the answer six slots, numbered 0 to 5 from the left. Number the digit positions from the left too: inum1jnum2
The last digits, 3 (ijiji + j + 1ij
The picture below places all nine digit products of 123 × 456 that way.
Each blue row is one digit of 123 times 456, already in its slots. Follow the orange column, slot 3: it collects 12 from 3 × 4, 10 from 2 × 5 and 6 from 1 × 6. In the row labelled "sum in the slot" they add up to 28.
A slot can show only one digit, so the sums are fixed from the right, as on paper. Slot 5 holds 18: it keeps the 8 and carries 1 into slot 4, which makes 28 there. Slot 4 keeps 8 and carries 2, so slot 3 becomes 30, keeps 0 and carries 3. The row labelled "digit after carrying" shows the result, 0, 5, 6, 0, 8 and 8. The 0 in slot 0 is not part of the answer, which is 56088.
So the shifted rows are never needed. Every digit product goes straight into slot i + j + 1
Solution Approach
Four things remain to decide: how many slots to make, in which order to fill them and carry, whether the numbers in the slots stay small, and what to do with zeros at the front.
The number of slots
How many slots does a product of any two strings need? If num1num2
Filling the slots and carrying
Must the column sums be added up first, as in the picture? No, the carrying can happen as the products arrive. Take the digits of num1num2
In 123 × 456, the first product is 3 × 6 = 18: slot 5 keeps 8 and slot 4 gets 1. The next is 3 × 5 = 15, which joins that 1 in slot 4 to make 16, so slot 4 keeps 6 and slot 3 gets 1. After all nine products, the slots hold 0, 5, 6, 0, 8 and 8, the same as the row labelled "digit after carrying".
The paper way, building each shifted row as a string and adding it to a running total, would also work. But it makes m rows of n or more digits, and one string addition per row. The slots skip those strings and do the same additions in one array.
How big a slot can get
Could a slot outgrow an intlong
A test run backs this up. Multiplying 2,000 nines by 2,000 nines, where every digit product is the biggest possible, no slot went above 18, no total went above 99, and every slot ended as a single digit. Only digits are ever multiplied, so the length of the strings never makes any number in the array bigger.
Zeros at the front
Is slot 0 always used? Not always: in 123 × 456 it stays 0, and in Example 1, 2 × 3 = 6 fills only the second of two slots. So the answer starts at the first slot that is not 0. If every slot is 0, as for "0""0"
Java Solution
The method multiply
- First, store the two lengths in
andm , and create the slots: ann arrayint of sizepos , all zeros.m + n - Walk the digits with two loops, one inside the other. The outer loop moves
from the last digit ofi to the first. For eachnum1 , the inner loop movesi from the last digit ofj to the first.num2 - Inside, turn the two characters into digits by subtracting
, so'0' is 5, and multiply them into'5' - '0' .mul - Add
to what slotmul holds, givingi + j + 1 . Keepsum , its last digit, in that slot, and addsum % 10 , the carry, to slotsum / 10 .i + j - After the loops, copy the slots into
, asb that collects the answer one digit at a time, skipping zeros until the first digit that is not 0.StringBuilder - If
is still empty, every slot was 0 and the method returnssb . Otherwise it returns the digits in"0" .sb
The main"0"longlong
public class MultiplyStrings {
public static String multiply(String num1, String num2) {
int m = num1.length();
int n = num2.length();
int[] pos = new int[m + n]; // the product has at most m + n digits
for (int i = m - 1; i >= 0; i--) {
for (int j = n - 1; j >= 0; j--) {
int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
int sum = mul + pos[i + j + 1]; // digits i and j land in slot i + j + 1
pos[i + j + 1] = sum % 10; // keep one digit
pos[i + j] += sum / 10; // carry one slot to the left
}
}
StringBuilder sb = new StringBuilder();
for (int d : pos) {
if (sb.length() == 0 && d == 0) {
continue; // skip leading zeros
}
sb.append(d);
}
return sb.length() == 0 ? "0" : sb.toString();
}
public static void main(String[] args) {
System.out.println(multiply("2", "3"));
System.out.println(multiply("123", "456"));
System.out.println(multiply("0", "52"));
System.out.println(multiply("9", "9"));
System.out.println(multiply("999", "999"));
String max = String.valueOf(Long.MAX_VALUE);
System.out.println(multiply(max, "2"));
System.out.println(Long.MAX_VALUE * 2); // the same product in a long
System.out.println(multiply("99999999999999999999", "99999999999999999999"));
}
}
Running it prints:
6
56088
0
81
998001
18446744073709551614
-2
9999999999999999999800000000000000000001
The first line, 6, has no 0 in front, although pos[0, 6]"0"sb"0"
The sixth line, 18446744073709551614, is the biggest longlong
Complexity
Every pair of digits is multiplied once, and the slots are read once at the end.
- Time: O(m × n), because each of the m digits of
is multiplied once by each of the n digits ofnum1 , and building the string is one more pass over m + n slots.num2 - Space: O(m + n), because the
array has m + n slots andpos holds at most that many digits, while no shifted row is ever stored.sb
Adding two numbers written as strings, column by column with a carry, is the simpler sibling of this problem: see