Multiply Large Numbers (Strings)
Problem
Two non-negative whole numbers are given as words of digits. They can have hundreds of digits, so no built-in number type can hold them. Print their product as a number without leading zeros. Do not use big-number libraries; multiply digit by digit like on paper.
Constraints
- 1 <= length <= 500
Examples
Input
123 456
Output
56088
Solutions
This is school multiplication in code. It is O(m * n); faster algorithms (Karatsuba) exist, but this is what BigInteger does for short numbers. A digit position can briefly hold a value above 9, which is fixed when the carry is processed by the next iteration.
/*
* Problem : Process two words.
* Input : Two words separated by a space.
* Output : The product.
* Approach: Two digit words.
* 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 number with m digits times a number with n digits has at most m + n digits.
int[] product = new int[a.length() + b.length()];
// Step 2: Multiply each digit pair. Put the result at i + j + 1 and carry to i + j.
for (int i = a.length() - 1; i >= 0; i--) {
for (int j = b.length() - 1; j >= 0; j--) {
int sum = (a.charAt(i) - '0') * (b.charAt(j) - '0') + product[i + j + 1];
product[i + j + 1] = sum % 10;
product[i + j] += sum / 10;
}
}
// Step 3: Skip leading zeros, then write the digits.
StringBuilder result = new StringBuilder();
for (int digit : product) {
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 (1)
- Why does the product have at most m + n digits?