PBNick
PBNick

Reputation: 55

How to compare to BigInts in Java to determine which one is the larger BigInt

I'm trying to compare two BigInts that were manually created and did not use the built-in BigInt class. Right now I'm getting hung up trying to be able to determine how to find the bigger number of the 2. For example if I want to find which number is bigger between 123 and 134, and I pass in both BigInts I want to return a false if 123 is the first number passed or True if the second number is passed. Please see the code below:

private boolean thisBigIntGreaterThanOrEqualToOther(BigInt b1, BigInt b2){
      boolean value = true;
      if(b1.bigInt.size() >= b2.bigInt.size()){
          for(int i = 0; i < b2.bigInt.size(); i++){
              if(b1.bigInt.get(i) >= b2.bigInt.get(i)){
                  value = true;
              }
              else{
                 value = false;
              }
          }
      }
      else{
          value = false;
      }
      return value;
  }

As you can see in my code I thought about trying to compare each digit, but I run into an issue when I get to 1's for each number, it sets the value to true.

BigInt Class Below:

    public class BigInt {

       //Instance variables for the class, a boolean for the sign and an ArrayList to store the input String

       private boolean pos = true;
       private ArrayList<Integer> bigInt = new ArrayList<Integer>();

       //No argument constructor, creates a big integer of value zero

       public BigInt () {
           this.pos = true;



       }

     //Constructor for big integers input as int

       public BigInt (int newBigInt) {
          String inputInt = Integer.toString(newBigInt);
           inputInt = handleSign(inputInt);
           inputInt = checkNumber(inputInt);
           for(int i = inputInt.length() - 1; i >=0; i--) {
               bigInt.add(Integer.parseInt(inputInt.substring(i, i+1)));
           }
       }

       //Constructor for big integers input as strings

       public BigInt (String newBigInt) {

           newBigInt = handleSign(newBigInt);
           newBigInt = checkNumber(newBigInt);
           for(int i = newBigInt.length() - 1; i >=0; i--) {
               bigInt.add(Integer.parseInt(newBigInt.substring(i, i+1)));
           }
       }
private String handleSign(String num) {

       if(num.charAt(0) == '+' || num.charAt(0) == '-') {
           if(num.length() == 1) {
               throw new ErrorMessage("Invalid value: sign only, no integer.");
           }

           if(num.charAt(0) == '-') {
               this.pos = false;
           }

           else {
               this.pos = true;
           }
           num = num.substring(1);
       }

       return num;
   }
   // Private method to remove leading zeros from add/subtract methods

   private BigInt removeZeros(BigInt result){

       for(int i = 0; i < result.bigInt.size(); i++){
           if(result.bigInt.get(i) == 0){
               result.bigInt.remove(i);
           }
       }
       return result;
   }

   //Private method to check the number; remove leading zeros and check for leading spaces (throw error message)

   private String checkNumber(String num) {

       if(num.charAt(0) == ' ') {
           throw new ErrorMessage("Invalid value: leading blank space.");
       }
       if(num.charAt(0) == '0'){
           while(num.length() > 1 && num.charAt(0) == '0') {
               num = num.substring(1);
           }
       }
       return num;
   }

   //toString method

public String toString() {

       String answer = "";
       for(int i = bigInt.size() - 1; i >=0; i--) {
           answer = answer + bigInt.get(i);
       }
       if(this.pos == false){
           return "-" + answer;
       }
    return answer;

Upvotes: 0

Views: 1046

Answers (1)

MartinS
MartinS

Reputation: 2790

The method to compare two BigInts is broken in several ways:

1. You iterate in the wrong direction:

for(int i = 0; i < b2.bigInt.size(); i++)

You start from the least significant digit which means 20 would be considered smaller than 11. Change it to

for(int i = b2.bigInt.size() - 1; i >= 0 ; i--)

2. You override the result of the comparison

If your code reaches the point where it sets value = false; it does not return or exit the loop. That means that in the next iteration the value gets overriden. That means suddenly 13 and 23 are considered equal.

BigInt c = new BigInt("13");
BigInt d = new BigInt("23");
System.out.println(BigInt.thisBigIntGreaterThanOrEqualToOther(c, d));
System.out.println(BigInt.thisBigIntGreaterThanOrEqualToOther(d, c));

The output is

true
true

Change value = false; to return false;

3. You do not check whether b1.bigInt.size() > b2.bigInt.size()

This results in your method returning that 131 is smaller than 23.

Change your code in the following way:

if(b1.bigInt.size() > b2.bigInt.size()){
  return true;
} else if(b1.bigInt.size() < b2.bigInt.size()){
  return false;
} else {
  // the other comparison code
}

Some final remarks:

It is good design to implement the Comparable interface as it allows you to use many library methods with your class.

EDIT: code now does not use library functions anymore

public class BigInt implements Comparable<BigInt> {

    ...

    @Override
    public int compareTo(BigInt other) {
        int c = this.bigInt.size() - other.bigInt.size();
        if (c != 0) {
            return c;
        } else {
            for (int i = this.bigInt.size() - 1; i >= 0; i--) {
                c = this.bigInt.get(i) - other.bigInt.get(i);
                if (c != 0) {
                    return c;
                }
            }
            return 0;
        }
    }
}

Upvotes: 3

Related Questions