codekofi
← All problems

Problem 24

Medium

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1string solution(const string& a, const string& b) {
2
3 if (a == "0" || b == "0") {
4 return "0";
5 }
6
7 int m = a.size();
8 int n = b.size();
9 vector<int> digits(m + n, 0);
10
11 for (int i = m - 1; i >= 0; i--) {
12 for (int j = n - 1; j >= 0; j--) {
13
14 int product = (a[i] - '0') * (b[j] - '0');
15 int low = i + j + 1;
16 int total = product + digits[low];
17
18 digits[low] = total % 10;
19 digits[i + j] += total / 10;
20 }
21 }
22
23 string ans;
24
25 for (int d : digits) {
26
27 if (ans.empty() && d == 0) {
28 continue;
29 }
30
31 ans += char('0' + d);
32 }
33
34 if (ans.empty()) {
35 return "0";
36 }
37
38 return ans;
39}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.