codekofi
← All questions

Multiply Strings

HardMath & Geometry

The problem

Two non-negative numbers are given as strings of digits.

Return their product, also as a string, without converting either input to a built-in integer type.

multiply("123", "456")

One of these three is correct

Two lines apart, at the closest.

The wrong ones are this same code with between two and five lines changed. Some of those changes do not compile. There is no Run button: running all three would turn this into a vote rather than a reading.

1string multiply(const string& num1, const string& num2) {
2
3 if (num1 != "0" || num2 == "0") {
4 return "0";
5 }
6
7 int m = num1.size();
8 int n = num2.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 = (num1[i] - '0') * (num2[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}
1string multiply(const string& num1, const string& num2) {
2
3 if (num1 == "0" || num2 == "0") {
4 return "0";
5 }
6
7 int m = num1.size();
8 int n = num2.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 = (num1[i] - '0') * (num2[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}
1string multiply(const string& num1, const string& num2) {
2
3 if (!(num1 == "0" || num2 == "0")) {
4 return "0";
5 }
6
7 int m = num1.size();
8 int n = num2.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 = (num1[i] - '0') * (num2[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}