1
- /* *
1
+ /*
2
2
* Description: BigInt (Big Integer library)
3
3
* Usage: See constructors, operators like +, -, *, /, >, >=, <, <=, ==, toString
4
4
* Note: Remove references '&' in overloaded operators for chaining operations.
@@ -49,7 +49,7 @@ class Bigint {
49
49
50
50
// Put everything back to original state
51
51
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 ' ;
53
53
54
54
return len;
55
55
}
@@ -83,20 +83,20 @@ class Bigint {
83
83
}
84
84
85
85
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
+ }
100
100
101
101
// Logical Operations
102
102
bool equals (char *X, int lenX, char *Y, int lenY) {
@@ -212,7 +212,10 @@ class Bigint {
212
212
string toString () {
213
213
string s (x, x+length);
214
214
reverse (s.begin (), s.end ());
215
- return trimZeros (s);
215
+ s = trimZeros (s);
216
+ if (s.length () == 0 )
217
+ return " 0" ;
218
+ return s;
216
219
}
217
220
218
221
friend std::ostream& operator <<(ostream &o, Bigint v) {
@@ -225,10 +228,13 @@ int main() {
225
228
Bigint A (" 123456789" ); // Construct Bigint using string representation
226
229
Bigint B (987654321 ); // Construct Bigint using integer representation
227
230
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;
231
236
// logical operations
232
237
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;
234
240
}
0 commit comments