[Geeks for Geeks] Multiply two strings

Multiply two strings

Given two numbers as strings s1 and s2. Calculate their Product.

Note: The numbers can be negative.

  • Time : O(nm)
  • Space : O(n + m)
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
class Solution{
public:
/*You are required to complete below function */
string multiplyStrings(string s1, string s2) {
reverse(begin(s1), end(s1));
reverse(begin(s2), end(s2));
int sign = 1, n = s1.length(), m = s2.length();
if(s1.back() == '-') {
sign = -sign;
s1.pop_back();
}
if(s2.back() == '-') {
sign = -sign;
s2.pop_back();
}
string res(n + m, '0');

for(int i = 0; i < n; i++) {
int carry = 0;
for(int j = 0; j < m; j++) {
int mul = carry + (s1[i] & 0b1111) * (s2[j] & 0b1111) + (res[i + j] & 0b1111);
carry = mul / 10;
mul = mul % 10;
res[i + j] = (mul | 0b110000);
}
int j = m;
while(carry) {
int sum = carry + (res[i + j] & 0b1111);
carry = sum / 10;
sum = sum % 10;
res[i + j] = (sum | 0b110000);
}
}

while(!res.empty() and res.back() == '0') res.pop_back();
if(!res.empty() and sign == -1) res.push_back('-');
reverse(begin(res), end(res));
return res.empty() ? "0" : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/22/PS/GeeksforGeeks/multiply-two-strings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.