-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathMultiply_two_strings.cpp
More file actions
76 lines (65 loc) · 1.63 KB
/
Copy pathMultiply_two_strings.cpp
File metadata and controls
76 lines (65 loc) · 1.63 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include<bits/stdc++.h>
using namespace std;
#include<string>
class Solution{
public:
string multiplyStrings(string s1, string s2) {
if(s1.equals("0") || s2.equals("0")){
return "0";
}
int aLen=s1.length();
int bLen=s2.length();
boolean minus=false;
if(s1.charAt(0)=='-' && s2.charAt(0)=='-'){
s1=s1.substring(1);
aLen--;
s2=s2.substring(1);
bLen--;
}
else if(s1.charAt(0)=='-'){
s1=s1.substring(1);
aLen--;
minus true;
}
else if(s2.charAt(0)=='-'){
s2=s2.substring(1);
bLen--;
minus true;
}
int len=aLen+bLen+1;
int res[]=new int[len];
int carry=0;
for(int i=0; i<bLen; i++){
int x=Integer.parseInt(s2.substring(bLen-1-i,bLen-i));
for(int j=0; j<aLen; j++){
int y=Integer.parseInt(s1.substring(aLen-1-j,aLen-j));
res[len-1-i-j] += x*y + carry;
carry= res[len-1-i-j]/10;
res[len-1-i-j]%=10;
}
if(carry!=0){
res[len-1-i-aLen]=carry;
carry=0;
}
}
string op="";
if(minus)
op="-";
for(int i=0; i<len; i++){
op=+res[i];
}
return op;
}
};
int main() {
int t;
cin>>t;
while(t--)
{
string a;
string b;
cin>>a>>b;
Solution obj;
cout<<obj.multiplyStrings(a,b)<<endl;
}
}