-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddTwoNumbers.cpp
More file actions
62 lines (56 loc) · 1.1 KB
/
AddTwoNumbers.cpp
File metadata and controls
62 lines (56 loc) · 1.1 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
/*
Problem: Add two integers
Description
Compute the sum of two integers a and b.
Input
Line 1 contains two integers a and b (0 <= a, b <= 10^19)
Ouput
Write the sum of a and b
Example
Input
3 5
Output
8
*/
#include <bits/stdc++.h>
using namespace std;
int main() {
string a, b;
cin >> a;
cin >> b;
int carry = 0;
int l1 = a.length(), l2 = b.length();
// b lớn hơn
if (l1 > l2)
{
swap(a, b);
}
stack<int> result;
int indexOfb = l2;
for (int i = l1-1; i >= 0; i--)
{
indexOfb--;
int sumOfDigit = (a[i]-'0') + (b[indexOfb]-'0') + carry;
result.push(sumOfDigit % 10);
carry = sumOfDigit / 10;
}
if (indexOfb == 0)
{
if (carry > 0) result.push(carry);
} else
{
for (int j = indexOfb-1; j >= 0; j--)
{
int sum = (b[j]-'0') + carry;
result.push(sum % 10);
carry = sum / 10;
}
if (carry > 0) result.push(carry);
}
while (!result.empty())
{
printf("%d",result.top());
result.pop();
}
return 0;
}