Big numbers selfmade: Part 7/14: Comparison
We want to be able to compare two of our objects - for example, to use them as keys in a SortedMap or similar structure. So, we implement Comparable<DecimalBigInt> and its compareTo method.
This method should return 0 if the compared objects are equal, a negative value if this is smaller than that and a positive value if this is bigger than that.
public int compareTo(DecimalBigInt that) {
How to know if one of our numbers is bigger than another? First, we compare the length of the arrays. As we took care not to induce any leading zeros (did we?), the longer array should have the bigger number.
if(this.digits.length < that.digits.length) {
return -1;
}
if (that.digits.length < this.digits.length) {
return 1;
}
If the length are same, we can compare digit-wise. Since we use big endian representation (i.e. the big end comes first), we start at the beginning.
for(int i = 0; i < this.digits.length; i++) {
if(this.digits[i] < that.digits[i]) {
return -1;
}
if(that.digits[i] < this.digits[i]) {
return 1;
}
}
If everything was same, obviously our numbers are identical, and we can return 0.
return 0;
}
Actually, we did not yet make sure there are no leading zeros: we will do this in the next part.
0: introduction, 1: number representation, 2: conversion from decimal format, 3: decimal formatting, 4: addition, 5: multiplication, 6: factorials, 7: comparison, 8: normalizing, 9: equals/hashCode, 10: converting between arbitrary radix systems, 11: converting from arbitrary radix, 12: division by small numbers, 13: conversion to arbitrary radix, 14: missing bits - Original question - Full code