Skip to content

Commit

Permalink
fix comparison bug with leading zeros
Browse files Browse the repository at this point in the history
  • Loading branch information
Limeoats committed Apr 29, 2017
1 parent 375e0d1 commit e4bd192
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 5 deletions.
2 changes: 2 additions & 0 deletions bin/BigNumber/include/bignumber.h
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ class BigNumber {
* @return The BigNumber after negation
*/
BigNumber negate();

BigNumber trimLeadingZeros();

//@{
/**
Expand Down
Binary file modified bin/BigNumber/lib/libBigNumber.a
Binary file not shown.
1 change: 1 addition & 0 deletions main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ int main() {
assert(BigNumber("-5") >= BigNumber("-10"));
assert(BigNumber("0") >= BigNumber("0"));
assert(BigNumber("32") >= BigNumber("-32"));
assert(BigNumber("2") >= BigNumber("0001"));

//Less than or equal to
assert(BigNumber("5") <= BigNumber("10"));
Expand Down
21 changes: 16 additions & 5 deletions src/bignumber.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,14 @@ BigNumber BigNumber::negate() {
return *this;
}

BigNumber BigNumber::trimLeadingZeros() {
BigNumber b = *this;
if (b._numberString.find_first_not_of('0') != std::string::npos) {
b.setString(b._numberString.erase(0, b._numberString.find_first_not_of('0')));
}
return b;
}

bool BigNumber::equals(const BigNumber &other) {
return this->_numberString == other._numberString;
}
Expand Down Expand Up @@ -461,21 +469,24 @@ bool operator>(BigNumber b1, const BigNumber &b2) {
return !(b1.isNegative() && !b2.isNegative());
}
}
if (b1 == b2) {
b1 = b1.trimLeadingZeros();
auto c = BigNumber(b2);
c = c.trimLeadingZeros();
if (b1 == c) {
return false;
}
if (b1._numberString.size() > b2._numberString.size()) {
if (b1._numberString.size() > c._numberString.size()) {
return true;
}
else if (b2._numberString.size() > b1._numberString.size()) {
else if (c._numberString.size() > b1._numberString.size()) {
return false;
}
else {
for (unsigned int i = 0; i < b1._numberString.size(); ++i) {
if (b1[i] == static_cast<unsigned int>(b2._numberString[i] - '0')) {
if (b1[i] == static_cast<unsigned int>(c._numberString[i] - '0')) {
continue;
}
return b1[i] > static_cast<unsigned int>(b2._numberString[i] - '0');
return b1[i] > static_cast<unsigned int>(c._numberString[i] - '0');
}
}
return false;
Expand Down
2 changes: 2 additions & 0 deletions src/bignumber.h
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ class BigNumber {
* @return The BigNumber after negation
*/
BigNumber negate();

BigNumber trimLeadingZeros();

//@{
/**
Expand Down

0 comments on commit e4bd192

Please sign in to comment.