-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuva424.cpp
101 lines (91 loc) · 2.05 KB
/
uva424.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
/*
* UVa Online Judge - Problem 424
*/
#include <iostream>
#include <stack>
#include <vector>
#include <sstream>
#include <algorithm>
class VeryLongInteger
{
private:
std::vector<int> digits;
public:
VeryLongInteger(std::string strValue);
void add(VeryLongInteger vli);
std::string toString();
};
VeryLongInteger::VeryLongInteger(std::string strValue)
{
int length = strValue.length();
std::stack<int> tempStack;
for (int i=0; i<length; i++) {
tempStack.push(strValue[i]-'0');
}
for (int i=0; i<length; i++) {
digits.push_back(tempStack.top());
tempStack.pop();
}
}
void VeryLongInteger::add(VeryLongInteger vli)
{
int minLength = std::min(digits.size(), vli.digits.size());
int maxLength = std::max(digits.size(), vli.digits.size());
std::vector<int> oldDigits = digits;
digits.clear();
int carry = 0;
for (int i=0; i<minLength; i++)
{
int sum = oldDigits[i] + vli.digits[i] + carry;
carry = sum/10;
sum = sum%10;
digits.push_back(sum);
}
if (oldDigits.size() > vli.digits.size())
{
for (int i=minLength; i<maxLength; i++)
{
int sum = oldDigits[i] + carry;
carry = sum/10;
sum = sum%10;
digits.push_back(sum);
}
}
else
{
for (int i=minLength; i<maxLength; i++)
{
int sum = vli.digits[i] + carry;
carry = sum/10;
sum = sum%10;
digits.push_back(sum);
}
}
if (carry == 1)
{
digits.push_back(1);
}
}
std::string VeryLongInteger::toString()
{
std::stringstream result;
for (int i=digits.size()-1; i>=0; i--)
result << digits[i];
return result.str();
}
int main ()
{
VeryLongInteger sum("0");
while (1)
{
std::string number;
std::cin >> number;
if (number == "0")
{
std::cout << sum.toString() << std::endl;
return 0;
}
VeryLongInteger a(number);
sum.add(a);
}
}