-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day 186: Multiply two strings.cpp
59 lines (44 loc) · 1.33 KB
/
Day 186: Multiply two strings.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution{
public:
/*You are required to complete below function */
string multiplyStrings(string s1, string s2) {
bool neg = 0;
if(s1[0] == '-'){
neg ^= 1;
s1 = s1.substr(1);
}
if(s2[0] == '-'){
neg ^= 1;
s2 = s2.substr(1);
}
reverse(s1.begin(), s1.end());
reverse(s2.begin(), s2.end());
int n = s1.size();
int m = s2.size();
vector<int> res(n + m + 20, 0);
for(int i = 0; i < m; i++){
int pos = i;
int x = s2[i] - '0';
for(int j = 0; j < n; j++){
int y = s1[j] - '0';
res[pos] += x * y;
if(res[pos] > 9){
res[pos + 1] += res[pos] / 10;
res[pos] = res[pos] % 10;
}
++pos;
}
}
bool found = 0;
string ans = "";
for(int i = res.size() - 1; i > -1; i--){
if(res[i])
found = 1;
if(found)
ans += (char)(res[i] + '0');
}
if(neg)
ans = '-' + ans;
return ans;
}
};