-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathString Multiplcation.cpp
More file actions
107 lines (86 loc) · 2.28 KB
/
Copy pathString Multiplcation.cpp
File metadata and controls
107 lines (86 loc) · 2.28 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
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
107
// C++ program to multiply two numbers represented
// as strings.
#include<bits/stdc++.h>
using namespace std;
// Multiplies str1 and str2, and prints result.
string multiply(string num1, string num2)
{
int n1 = num1.size();
int n2 = num2.size();
if (n1 == 0 || n2 == 0)
return "0";
// will keep the result number in vector
// in reverse order
vector<int> result(n1 + n2, 0);
// Below two indexes are used to find positions
// in result.
int i_n1 = 0;
int i_n2 = 0;
// Go from right to left in num1
for (int i=n1-1; i>=0; i--)
{
int carry = 0;
int n1 = num1[i] - '0';
// To shift position to left after every
// multiplication of a digit in num2
i_n2 = 0;
// Go from right to left in num2
for (int j=n2-1; j>=0; j--)
{
// Take current digit of second number
int n2 = num2[j] - '0';
// Multiply with current digit of first number
// and add result to previously stored result
// at current position.
int sum = n1*n2 + result[i_n1 + i_n2] + carry;
// Carry for next iteration
carry = sum/10;
// Store result
result[i_n1 + i_n2] = sum % 10;
i_n2++;
}
// store carry in next cell
if (carry > 0)
result[i_n1 + i_n2] += carry;
// To shift position to left after every
// multiplication of a digit in num1.
i_n1++;
}
// ignore '0's from the right
int i = result.size() - 1;
while (i>=0 && result[i] == 0)
i--;
// If all were '0's - means either both or
// one of num1 or num2 were '0'
if (i == -1)
return "0";
// generate the result string
string s = "";
while (i >= 0)
s += std::to_string(result[i--]);
return s;
}
// Driver code
int main()
{
string str1 = "3141592653589793238462643383279502884197169399375105820974944592";
string str2 = "2718281828459045235360287471352662497757247093699959574966967627";
if((str1.at(0) == '-' || str2.at(0) == '-') &&
(str1.at(0) != '-' || str2.at(0) != '-' ))
cout<<"-";
if(str1.at(0) == '-' && str2.at(0)!='-')
{
str1 = str1.substr(1);
}
else if(str1.at(0) != '-' && str2.at(0) == '-')
{
str2 = str2.substr(1);
}
else if(str1.at(0) == '-' && str2.at(0) == '-')
{
str1 = str1.substr(1);
str2 = str2.substr(1);
}
cout << multiply(str1, str2);
return 0;
}