-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBigInt.cpp
More file actions
115 lines (98 loc) · 2.32 KB
/
Copy pathBigInt.cpp
File metadata and controls
115 lines (98 loc) · 2.32 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
108
109
110
111
112
113
114
115
#include "BigInt.h"
#include <stdexcept>
#include <string>
// Core representation, construction and invariant maintenance.
BigInt::BigInt()
{
this->digits.push_back(0);
this->negative = false;
}
BigInt::BigInt(int value)
{
this->negative = value < 0;
do
{
int singleValue = value % 10;
if (singleValue < 0)
{
singleValue = -singleValue;
}
this->digits.push_back(singleValue);
value = value / 10;
} while (value != 0);
}
BigInt::BigInt(const std::string &text)
{
this->negative = false;
char firstDigit = 0;
if (text.empty() || text == "-" || text == "+")
{
throw std::invalid_argument("BigInt: input non valido");
}
if (text[0] == '-')
{
this->negative = true;
firstDigit = 1;
}
else if (text[0] == '+')
{
firstDigit = 1;
}
for (int i = text.length() - 1; i >= firstDigit; i--)
{
char value = text[i];
if (value >= '0' && value <= '9')
{
int number = value - '0';
this->digits.push_back(number);
}
else
{
throw std::invalid_argument("BigInt: input non valido");
}
}
this->Normalize();
}
void BigInt::Normalize()
{
if (digits.empty())
{
this->digits.push_back(0);
}
while (digits.size() > 1 && digits.back() == 0)
{
this->digits.pop_back();
}
if (digits.front() == 0 && digits.size() == 1)
{
this->negative = false;
}
}
bool BigInt::IsZero() const
{
return this->digits.size() == 1 && this->digits.at(0) == 0;
}
BigInt::MagnitudeComparison BigInt::CompareMagnitude(const BigInt &other) const
{
if (this->digits.size() < other.digits.size())
{
return MagnitudeComparison::Lesser;
}
else if (this->digits.size() > other.digits.size())
{
return MagnitudeComparison::Greater;
}
for (std::size_t i = this->digits.size(); i > 0; --i)
{
std::size_t index = i - 1;
if (this->digits.at(index) > other.digits.at(index))
{
return MagnitudeComparison::Greater;
}
else if (this->digits.at(index) < other.digits.at(index))
{
return MagnitudeComparison::Lesser;
}
}
return MagnitudeComparison::Equal;
}