Multiply Two Huge Numbers (Strings)

Problem

Two non-negative numbers are given as digit strings on two lines. They can have up to 100 digits. Print their product. Do not use BigInteger or BigInt. Multiply the digits by hand, as on paper.

Constraints

  • 0 <= each number < 10^100

Examples

Input

12
12

Output

144

Solutions

Best approachTime O(m * n)Space O(m + n)

This is school multiplication. Digit i of a and digit j of b affect the place i + j + 1 (and the carry goes to i + j). We store all places in one array, then print it without leading zeros.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Multiply two big numbers given as text.
 * Input   : Two lines with digits.
 * Output  : The product.
 * Approach: Digit i times digit j goes to place i + j + 1.
 * Time    : O(m * n)
 * Space   : O(m + n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static String solve(String a, String b) {
        // Step 1: A product of an m-digit and an n-digit number has at most m + n digits.
        int[] digits = new int[a.length() + b.length()];

        // Step 2: Multiply every digit of a with every digit of b. Digit i and j land at place i + j + 1.
        for (int i = a.length() - 1; i >= 0; i--) {
            for (int j = b.length() - 1; j >= 0; j--) {
                int product = (a.charAt(i) - '0') * (b.charAt(j) - '0');
                int sum = product + digits[i + j + 1];

                // Step 3: Keep one digit at this place and move the carry one place to the left.
                digits[i + j + 1] = sum % 10;
                digits[i + j] += sum / 10;
            }
        }

        // Step 4: Skip leading zeros, but keep at least one digit.
        StringBuilder result = new StringBuilder();
        for (int digit : digits) {
            if (result.length() > 0 || digit != 0) {
                result.append(digit);
            }
        }
        return result.length() == 0 ? "0" : result.toString();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String a = scanner.next();
        String b = scanner.next();
        System.out.println(solve(a, b));
    }
}
Hints (2)
  1. How many digits can the product have?
  2. Which place gets the digit from positions i and j?