Cryptography Reference
In-Depth Information
This is how we normally compare integers ourselves, and writing the lessThan(Int)
method in Java isn't terribly difficult.
public boolean lessThan(Int other) {
//Start by assuming this is less than other
boolean answer=false;
//Both Ints are nonnegative here
if (!negative&&!other.negative) {
//If they are the same length, must compare the digits
if (digits.length==other.digits.length) {
int i=0;
while (i<this.digits.length&&digits[i]==other.digits[i]) i++;
//Each digit of this was less than each digit of other
if (i<this.digits.length)
if (digits[i]<other.digits[i])
answer=true;
//this has smaller length than other-must be less than
} else if (digits.length<other.digits.length) answer=true;
//If both Ints negative, do the reverse of the above comparisons
} else if (negative&&other.negative) {
if (digits.length==other.digits.length) {
int i=0;
while (i<this.digits.length&&digits[i]==other.digits[i]) i++;
if (i<this.digits.length)
if (digits[i]>other.digits[i])
answer=true;
} else if (other.digits.length<digits.length) answer=true;
//If this is negative and other nonnegative, must be less than
} else if (negative&&!other.negative) answer=true;
//Otherwise, this is nonnegative and other negative
//Return answer, which was initialized to false
return answer;
}
The code to determine whether or not two Ints are equal should now be very simple to
write.
public boolean equals(Int other) {
boolean answer=true;
//Check if same sign
if (negative!=other.negative) answer=false;
//Check if different lengths
else if (digits.length!=other.digits.length) answer=false;
//If same length and sign, compare each digit
else for (int i=0;i<digits.length;i++)
Search WWH ::




Custom Search