Multiply Strings LeetCode solution in C++

1
class Solution {
2
void compute(string &num, int dig, int ind, string &ans) {
3
int c = 0; // carry digit..
4
int i = num.size() - 1;
5
// again travarsing the string in reverse
6
while (i >= 0) {
7
int mul = dig * (num[i] - '0') + c; // the curr digit's multiplication
8
c = mul / 10; // carry update..
9
mul %= 10; // mul update in a single digit..
10
if (ind >= ans.length()) { // here if the index where we'll put the value
11
// is out of bounds...
12
ans.push_back('0' + mul);
13
} else {
14
// here adding the val with the previous digit and further computing
15
// the carry...
16
mul += (ans[ind] - '0');
17
c += mul / 10;
18
mul %= 10;
19
ans[ind] = ('0' + mul);
20
}
21
i--;
22
ind++; // increment the index where we'll put the val;
23
}
24

25
if (c > 0) { // if carry is non-zero...
26
ans.push_back('0' + c);
27
}
28
}
29

30
public:
31
string multiply(string num1, string num2) {
32
string ans = ""; // the string which we have to return as answer..
33
if (num1 == "0" || num2 == "0") return "0"; // base case..
34
int ind = 0; // the index from which we'll add the multiplied value to the
35
// ans string
36
for (int i = num1.size() - 1; i >= 0; ind++, i--) {
37
// travarsing in reverse dir. on num1 and increasing ind bcz for every
38
// digit
39
// of num1 we'll add the multiplication in a index greater than the
40
// previous iteration
41
int dig = num1[i] - '0'; // the digit with which we'll multiply by num2..
42
compute(num2, dig, ind, ans); // function call for every digit and num2
43
}
44
// we have calculated the ans in a reverse way such that we can easily add
45
// a leading digit & now reversing it...
46
reverse(ans.begin(), ans.end());
47
return ans;
48
}
49
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0