Skip to content

Commit edf503d

Browse files
committed
bigint: fix: toString with value 0
1 parent 2d146b2 commit edf503d

File tree

1 file changed

+27
-21
lines changed

1 file changed

+27
-21
lines changed

src/bigint_library.cpp

+27-21
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/**
1+
/*
22
* Description: BigInt (Big Integer library)
33
* Usage: See constructors, operators like +, -, *, /, >, >=, <, <=, ==, toString
44
* Note: Remove references '&' in overloaded operators for chaining operations.
@@ -49,7 +49,7 @@ class Bigint {
4949

5050
//Put everything back to original state
5151
for (int i = 0; i < maxLen; i++) Y[i]=('9'-Y[i])+'0';
52-
X[lenX]='\0'; Y[lenY]='\0';
52+
X[lenX]='\0'; Y[lenY]='\0';
5353

5454
return len;
5555
}
@@ -83,20 +83,20 @@ class Bigint {
8383
}
8484

8585
template<class T>
86-
int divideNmodulo(char *X, int lenX, T divisor, char *Z, T &modulo) {
87-
int remainder = 0;
88-
int size = 0;
89-
for(int i = lenX-1; i >= 0; i--){
90-
remainder *= 10;
91-
remainder += X[i]- '0';
92-
Z[size++] = remainder/divisor + '0';
93-
remainder %= divisor;
94-
}
95-
Z[size]='\0';
96-
reverse(Z, Z+size);
97-
modulo = remainder;
98-
return size;
99-
}
86+
int divideNmodulo(char *X, int lenX, T divisor, char *Z, T &modulo) {
87+
int remainder = 0;
88+
int size = 0;
89+
for(int i = lenX-1; i >= 0; i--){
90+
remainder *= 10;
91+
remainder += X[i]- '0';
92+
Z[size++] = remainder/divisor + '0';
93+
remainder %= divisor;
94+
}
95+
Z[size]='\0';
96+
reverse(Z, Z+size);
97+
modulo = remainder;
98+
return size;
99+
}
100100

101101
//Logical Operations
102102
bool equals(char *X, int lenX, char *Y, int lenY) {
@@ -212,7 +212,10 @@ class Bigint {
212212
string toString() {
213213
string s(x, x+length);
214214
reverse(s.begin(), s.end());
215-
return trimZeros(s);
215+
s = trimZeros(s);
216+
if(s.length() == 0)
217+
return "0";
218+
return s;
216219
}
217220

218221
friend std::ostream& operator<<(ostream &o, Bigint v) {
@@ -225,10 +228,13 @@ int main() {
225228
Bigint A("123456789"); // Construct Bigint using string representation
226229
Bigint B(987654321); // Construct Bigint using integer representation
227230
Bigint C("456789");
228-
cout << A * B << endl; // Overridden ostream
229-
cout << A * B + C << endl; // Chaining operations
230-
cout << (A > B) << endl;
231+
Bigint D("0");
232+
cout << "A * B: " << A * B << endl; // Overridden ostream
233+
cout << "A * B + C: " << A * B + C << endl; // Chaining operations
234+
cout << "(A > B): " << (A > B) << endl;
235+
cout << "D: " << D << endl;
231236
// logical operations
232237
if (A > B) cout << "A is greater than B" << endl;
233-
else cout << "B is greater than A" << endl;
238+
if (B > A) cout << "B is greater than A" << endl;
239+
if (A == B) cout << "A is equal to B" << endl;
234240
}

0 commit comments

Comments
 (0)