-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathadd.cpp
More file actions
83 lines (74 loc) · 1.05 KB
/
add.cpp
File metadata and controls
83 lines (74 loc) · 1.05 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
#include<iostream>
#include<vector>
using namespace std;
void add(string, string);
int main()
{
int q;
cin >> q;
while(q > 0)
{
string a, b;
//cout << "Enter positive number 1:\n";
cin >> a;
//cout << "Enter positive number 2:\n";
cin >> b;
add(a, b);
q--;
}
return 0;
}
void add(string a, string b)
{
int l_a = a.size(), l_b = b.size();
vector<int> c(max(l_a + 1, l_b + 1), 0);
int i = l_a - 1, j = l_b - 1, k = 0;
int carry = 0, digit;
int flag = 0;
while(i >= 0 && j >= 0)
{
digit = (a[i] - '0') + (b[j] - '0') + carry;
c[k++] = digit % 10;
carry = digit / 10;
i--;
j--;
}
while(i >= 0)
{
digit = (a[i] - '0') + carry;
c[k++] = digit % 10;
carry = digit / 10;
i--;
}
while(j >= 0)
{
digit = (b[j] - '0') + carry;
c[k++] = digit % 10;
carry = digit / 10;
j--;
}
if(carry)
{
c[k++] = carry;
}
for(int i = 0; i < k; i++)
{
if(c[i])
flag = 1;
}
if(flag)
{
int i = k - 1;
while(!c[i])
{
i--;
}
for(; i >= 0; i--)
cout << c[i];
cout << '\n';
}
else
{
cout << "0\n";
}
}