-
Notifications
You must be signed in to change notification settings - Fork 1
/
Multiply two strings.cpp
106 lines (97 loc) · 2.43 KB
/
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/*
Given two numbers as strings. The numbers may be very large (may not fit in long long int),
the task is to find product of these two numbers.
*/
#include<bits/stdc++.h>
using namespace std;
bool isGreater(string, string);
void multiply(string, string);
string addString(string, string);
string _add(string, string);
int main(void){
int t;
string s1, s2;
cin >> t;
while(t--){
cin >> s1 >> s2;
if(!((s1[0] == '-' && s2[0] =='-') ||(s1[0] != '-' && s2[0] !='-')))
cout << "-";
if(s1[0] == '-')
s1.erase(s1.begin());
if(s2[0] == '-')
s2.erase(s2.begin());
multiply(s1, s2);
cout << endl;
}
return 0;
}
void multiply(string s1, string s2){
int l1, l2;
string res1, res2;
l1 = s1.length();
l2 = s2.length();
for(int j = l2 - 1, k = 0; j >= 0; j--, k++){
int c = 0;
res1.erase();
for(int i = l1 - 1; i >= 0; i--){
int temp = (s2[j] - '0') * (s1[i] - '0') + c;
char ld = (temp % 10) + '0';
res1 = ld + res1;
c = temp / 10;
}
while(c){
char ld = (c % 10) + '0';
res1 = ld + res1;
c /= 10;
}
int temp = k;
while(temp--)
res1.push_back('0');
res2 = addString(res1, res2);
}
cout << res2;
}
bool isGreater(string a, string b){
if(a.length() > b.length())
return true;
else if(a.length() < b.length())
return false;
else{
for(int i = 0; i < a.length(); i++){
if(a[i] > b[i])
return true;
else if(a[i] < b[i])
return false;
}
return true;
}
}
string addString(string a, string b){
if(isGreater(a, b))
return _add(a, b);
else
return _add(b, a);
}
string _add(string a, string b){
string res;
int c = 0;
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
for(int i = 0; i < b.length(); i++){
int temp = (a[i] - '0') + (b[i] - '0') + c;
res.push_back((temp % 10) + '0');
c = temp / 10;
}
for(int i = b.length(); i < a.length(); i++){
int temp = (a[i] - '0') + c;
res.push_back((temp % 10) + '0');
c = temp / 10;
}
while(c){
char ld = (c % 10) + '0';
res.push_back(ld);
c /= 10;
}
reverse(res.begin(), res.end());
return res;
}