Practice › Strings
Multiply Two Large Numbers
Medium · Strings · Asked at Meta, Amazon, Microsoft, Google
Two non-negative integers are given as strings (no leading zeros, except 0 itself). Print their product. Do not use a big-integer library — this is about the schoolbook algorithm.
Input
Two lines: the numbers a and b.
Output
The product a × b.
Constraints
- 1 ≤ |a|, |b| ≤ 1000
Digit a[i] × b[j] lands in position i + j + 1 of a result array of length |a| + |b|. Add all products, then sweep from the right carrying tens. Strip leading zeros at the end (but keep one zero).
Example 1
Input
2 3
Output
6
Example 2
Input
123 456
Output
56088
Hints
- Multiplying digit a[i] by digit b[j] contributes to one position of the result.
- In a result of length |a| + |b|, that position is i + j + 1 (counting from the left).
- Add all contributions, then fix the carries once from right to left.
Approach
Create an array res of |a| + |b| zeros. For every pair (i, j) add a[i] × b[j] to res[i + j + 1]. Then sweep from the right: res[k − 1] += res[k] / 10 and res[k] %= 10. Skip leading zeros when printing; if everything is zero (one input is 0), print 0. A product of an m-digit and an n-digit number has at most m + n digits, so the array is always big enough.
Complexity: O(|a| · |b|) time · O(|a| + |b|) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
string a, b;
cin >> a >> b;
int n = a.size(), m = b.size();
vector<long long> res(n + m, 0);
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) res[i + j + 1] += (a[i] - '0') * (b[j] - '0');
for (int k = n + m - 1; k > 0; k--) {
res[k - 1] += res[k] / 10;
res[k] %= 10;
}
string out;
for (long long d : res)
if (!(out.empty() && d == 0)) out += char('0' + d);
cout << (out.empty() ? "0" : out) << "\n";
return 0;
}Python solution
import sys
a, b = sys.stdin.read().split()[:2]
n, m = len(a), len(b)
res = [0] * (n + m)
da = [ord(c) - 48 for c in a]
db = [ord(c) - 48 for c in b]
for i in range(n):
x = da[i]
if x == 0:
continue
for j in range(m):
res[i + j + 1] += x * db[j]
for k in range(n + m - 1, 0, -1):
res[k - 1] += res[k] // 10
res[k] %= 10
out = "".join(map(str, res)).lstrip("0")
print(out or "0")Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String a = br.readLine().trim(), b = br.readLine().trim();
int n = a.length(), m = b.length();
long[] res = new long[n + m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) res[i + j + 1] += (a.charAt(i) - '0') * (b.charAt(j) - '0');
for (int k = n + m - 1; k > 0; k--) {
res[k - 1] += res[k] / 10;
res[k] %= 10;
}
StringBuilder out = new StringBuilder();
for (long d : res)
if (!(out.length() == 0 && d == 0)) out.append(d);
System.out.println(out.length() == 0 ? "0" : out.toString());
}
}Solve Multiply Two Large Numbers online · All practice problems