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 num1 and num2, written as strings of digits, return their product, also as a string. Do not turn the whole strings into numbers, and do not use BigInteger, the Java class for integers of any size.

Example 1
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2
Input: num1 = "123", num2 = "456"
Output: "56088"
Solution

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 long and multiply? The biggest long is 9,223,372,036,854,775,807, nineteen digits. The strings may be longer than that, and even two numbers that fit can have a product that does not: that biggest long times 2 already needs twenty digits. So the work has to happen digit by digit, as on paper.

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: i for a position in num1 and j for a position in num2.

The last digits, 3 (i = 2) and 6 (j = 2), make ones, so their product goes in slot 5, the last slot. Moving either digit one place to the left moves its product one slot to the left. Both facts fit one rule: the product of digit i and digit j goes to slot i + j + 1. For the 2 and the 5, i = 1 and j = 1, so their 10 lands in slot 3, the hundreds.

The picture below places all nine digit products of 123 × 456 that way.

123 times 456 with six slots, 0 to 5. The products of 3, 2 and 1 with 4, 5 and 6 each land in one slot. Slot 3 collects 12, 10 and 6, which sum to 28. The slot sums 0, 4, 13, 28, 27, 18 become the digits 0, 5, 6, 0, 8, 8 after carrying, so the answer is 56088.

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, and carrying turns the slots into the digits of the answer.

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 num1 has m digits, it is below 10m, and if num2 has n digits, it is below 10n. Their product is below 10m + n, so m + n slots always have room for every digit.

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 num1 from right to left, and for each one, the digits of num2 from right to left. Add each product to what its slot holds, keep the last digit of that total in the slot, and add the rest to the slot on its left.

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 int, the way the product outgrew a long? No. In the order the loops run, a slot holds at most two parts of at most 9 each: the digit it kept, or an earlier carry, plus one new carry. That makes at most 18. Adding a digit product of at most 9 × 9 = 81 gives at most 99, and the carry out of 99 is just 9.

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" times anything, the answer is "0".

Java Solution

The method multiply works in these steps:

  1. First, store the two lengths in m and n, and create the slots: an int array pos of size m + n, all zeros.
  2. Walk the digits with two loops, one inside the other. The outer loop moves i from the last digit of num1 to the first. For each i, the inner loop moves j from the last digit of num2 to the first.
  3. Inside, turn the two characters into digits by subtracting '0', so '5' - '0' is 5, and multiply them into mul.
  4. Add mul to what slot i + j + 1 holds, giving sum. Keep sum % 10, its last digit, in that slot, and add sum / 10, the carry, to slot i + j.
  5. After the loops, copy the slots into sb, a StringBuilder that collects the answer one digit at a time, skipping zeros until the first digit that is not 0.
  6. If sb is still empty, every slot was 0 and the method returns "0". Otherwise it returns the digits in sb.

The main method runs both examples, "0" times 52, 9 × 9 and 999 × 999, the biggest long times 2 next to the same product in a long, and two 20-digit strings of nines.

Java
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:

Output
6
56088
0
81
998001
18446744073709551614
-2
9999999999999999999800000000000000000001

The first line, 6, has no 0 in front, although pos was [0, 6]: the leading zero was skipped. In the third line, "0" times 52 left all three slots at 0, so sb stayed empty and the method returned "0". Both 9 × 9 = 81 and 999 × 999 = 998001 fill every slot.

The sixth line, 18446744073709551614, is the biggest long times 2, all twenty digits of it. The line under it is the same multiplication done in a long, and it prints -2: the true answer does not fit, so the result wraps around to a negative number. The last line is the 40-digit product of the two strings of nines: nineteen 9s, an 8, nineteen 0s and a 1.

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 num1 is multiplied once by each of the n digits of num2, and building the string is one more pass over m + n slots.
  • Space: O(m + n), because the pos array has m + n slots and sb holds at most that many digits, while no shifted row is ever stored.

Adding two numbers written as strings, column by column with a carry, is the simpler sibling of this problem: see Add Strings.