-
Notifications
You must be signed in to change notification settings - Fork 3
/
stringMathFunctions.cpp
98 lines (76 loc) · 1.84 KB
/
stringMathFunctions.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
string sum(string str1, string str2)
{
if (str1.length() > str2.length())
swap(str1, str2);
string str = "";
int n1 = str1.length(), n2 = str2.length();
reverse(str1.begin(), str1.end());
reverse(str2.begin(), str2.end());
int carry = 0;
for (int i=0; i<n1; i++)
{
int sum = ((str1[i]-'0')+(str2[i]-'0')+carry);
str.push_back(sum%10 + '0');
carry = sum/10;
}
for (int i=n1; i<n2; i++)
{
int sum = ((str2[i]-'0')+carry);
str.push_back(sum%10 + '0');
carry = sum/10;
}
if (carry)
str.push_back(carry+'0');
reverse(str.begin(), str.end());
return str;
}
string product(string num1, string num2)
{
int n1 = num1.size();
int n2 = num2.size();
if (n1 == 0 || n2 == 0)
return "0";
vector<int> result(n1 + n2, 0);
int i_n1 = 0;
int i_n2 = 0;
for (int i=n1-1; i>=0; i--)
{
int carry = 0;
int n1 = num1[i] - '0';
i_n2 = 0;
for (int j=n2-1; j>=0; j--)
{
int n2 = num2[j] - '0';
int sum = n1*n2 + result[i_n1 + i_n2] + carry;
carry = sum/10;
result[i_n1 + i_n2] = sum % 10;
i_n2++;
}
if (carry > 0)
result[i_n1 + i_n2] += carry;
i_n1++;
}
int i = result.size() - 1;
while (i>=0 && result[i] == 0)
i--;
if (i == -1)
return "0";
string s = "";
while (i >= 0)
s += std::to_string(result[i--]);
return s;
}
inline string divideby2(string a) {
int la = a.length();
if(la == 0) return a;
ll carry = 0;
string ans;
fo(i,0,la) {
int curr = 10*carry + (a[i] - '0');
carry = (curr%2);
ans += ((curr/2) + '0');
}
if(ans == "0") return ans;
if(ans[0] == '0') ans.erase(ans.begin());
return ans;
}