Question

In: Computer Science

For a project I have to implement a class called BigInteger, with a representative small set...

For a project I have to implement a class called BigInteger, with a representative small set of operations. (working with big integers that is far more digits that java's int data type will allow. Here's the code, including what I have so far. I would appreciate any help. thank you. i'm not sure if what i have is right (the only thing i wrote is under the public static BigInteger parse(String integer) we just have to implement that method.

package bigint;

/** * This class encapsulates a BigInteger, i.e. a positive or negative integer with * any number of digits, which overcomes the computer storage length limitation of * an integer. * */

public class BigInteger {

/** * True if this is a negative integer */

boolean negative;

/** * Number of digits in this integer

*/ int numDigits; /** * Reference to the first node of this integer's linked list representation * NOTE: The linked list stores the Least Significant Digit in the FIRST node. * For instance, the integer 235 would be stored as: * 5 --> 3 --> 2 * * Insignificant digits are not stored. So the integer 00235 will be stored as: * 5 --> 3 --> 2 (No zeros after the last 2) */

DigitNode front; /** * Initializes this integer to a positive number with zero digits, in other * words this is the 0 (zero) valued integer. */

public BigInteger() {

negative = false; numDigits = 0; front = null; }

/** * Parses an input integer string into a corresponding BigInteger instance. * A correctly formatted integer would have an optional sign as the first * character (no sign means positive), and at least one digit character * (including zero). * Examples of correct format, with corresponding values * Format Value * +0 0 * -0 0 * +123 123 * 1023 1023 * 0012 12 * 0 0 * -123 -123 * -001 -1 * +000 0 * * Leading and trailing spaces are ignored. So " +123 " will still parse * correctly, as +123, after ignoring leading and trailing spaces in the input * string. * * Spaces between digits are not ignored. So "12 345" will not parse as * an integer - the input is incorrectly formatted. * * An integer with value 0 will correspond to a null (empty) list - see the BigInteger * constructor * * @param integer Integer string that is to be parsed * @return BigInteger instance that stores the input integer. * @throws IllegalArgumentException If input is incorrectly formatted */

public static BigInteger parse(String integer)

throws IllegalArgumentException {

integer = integer.trim();

BigInteger bigInt = new BigInteger();

boolean negative = false; hasExplicitSign = false; int stringLength;

if(integer != null) {

stringLength = integer.length(); }else { throw new IllegalArgumentException("Please input a valid number"); }

if (stringLength==0) { throw new IllegalArgumentException("Please input a valid number"); } else

if(stringLength == 1 && integer.substring(0,1).compareTo("-") <= 0) {

throw new IllegalArgumentException("Please input a valid number."); } else

if(stringLength>0) {

int lastIndexNeg = -1; int lastIndexPos = -1;

for(int i = 0; i < stringLength; i++) {

char digitOrSign = integer.charAt(i); if(digitOrSign == '-') lastIndexNeg = i; else if(digitOrSign == '+')

lastIndexPos = i;

else if(!Character.isDigit(digitOrSign))

throw new IllegalArgumentException("Please input a valid number.");

if(lastIndexNeg > 0 || lastIndexPos > 0) {

throw new IllegalArgumentException("Please input a valid number.");

if(lastIndexNeg == 0) {

hasExplicitSign = true; negative = true; } else

if(lastIndexPos == 0) { hasExplicitSign = true; } if(hasExplicitSign) {

integer = integer.substring(1); stringLength--; }

if(stringLength==1 && integer.charAt(0) == '0') {

return bigInt; } } int lastDigit = Integer.parseInt(integer.substring(stringLength-1, stringLength));

bigInt.front = new DigitNode(lastDigit, null); } } } } /* IMPLEMENT THIS METHOD */ // following line is a placeholder for compilation return null; } /** * Adds the first and second big integers, and returns the result in a NEW BigInteger object. * DOES NOT MODIFY the input big integers. * * NOTE that either or both of the input big integers could be negative. * (Which means this method can effectively subtract as well.) * * @param first First big integer * @param second Second big integer * @return Result big integer */ public static BigInteger add(BigInteger first, BigInteger second) { /* IMPLEMENT THIS METHOD */ // following line is a placeholder for compilation return null; } /** * Returns the BigInteger obtained by multiplying the first big integer * with the second big integer * * This method DOES NOT MODIFY either of the input big integers * * @param first First big integer * @param second Second big integer * @return A new BigInteger which is the product of the first and second big integers */ public static BigInteger multiply(BigInteger first, BigInteger second) { /* IMPLEMENT THIS METHOD */ // following line is a placeholder for compilation return null; } /* (non-Javadoc) * @see java.lang.Object#toString() */

public String toString() {

if (front == null) { return "0"; }

String retval = front.digit + "";

for (DigitNode curr = front.next; curr != null; curr = curr.next)

{ retval = curr.digit + retval; }

if (negative) { retval = '-' + retval; }

return retval; } }

this is the other class digitalnode.java

package bigint;

/**
* This class encapsulates a linked list for a digit of a big integer.
public class DigitNode {
   /**
   * The digit
   */
   int digit;
  
   /**
   * Pointer to next digit in the linked list
   */
   DigitNode next;
  
   /**
   * Initializes this digit node with a digit and next pointer
   *
   * @param digit Digit
   * @param next Next pointer
   */
   DigitNode(int digit, DigitNode next) {
       this.digit = digit;
       this.next = next;
   }
  
   /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
   public String toString() {
       return digit + "";
   }
}

Solutions

Expert Solution

I have reimplemented the parse() method so it is simpler. I have also written a small test class to show it works correctly.
Please do rate the answer if it helped. Thank you

BigIntTest.java
-----------
package bigint;

public class BigIntTest {


   public static void main(String[] args) {
       String[] nums = { "+0", "-0", "+123", "1023", "0012 ", "0", "-123", "-001", "+000", "12 345", "12 a", "++00"};

       for(int i = 0; i < nums.length; i++) {
           try {
               BigInteger bint = BigInteger.parse(nums[i]);
               System.out.println("Parsed correctly " + bint);
           }
           catch(IllegalArgumentException e){
               System.out.println(e.getMessage());
           }
       }

   }
}

BigInteger.java
----------
package bigint;

/**
* * This class encapsulates a BigInteger, i.e. a positive or negative integer
* with * any number of digits, which overcomes the computer storage length
* limitation of * an integer. *
*/
public class BigInteger {
   /** * True if this is a negative integer */
   boolean negative;
   /**
   * Number of digits in this integer
   *
   */
   int numDigits;
   /**
   * * Reference to the first node of this integer's linked list representation *
   * NOTE: The linked list stores the Least Significant Digit in the FIRST node. *
   * For instance, the integer 235 would be stored as: * 5 --> 3 --> 2 * *
   * Insignificant digits are not stored. So the integer 00235 will be stored as:
   * * 5 --> 3 --> 2 (No zeros after the last 2)
   */
   DigitNode front;

   /**
   * * Initializes this integer to a positive number with zero digits, in other *
   * words this is the 0 (zero) valued integer.
   */
   public BigInteger() {
       negative = false;
       numDigits = 0;
       front = null;
   }

   /**
   * * Parses an input integer string into a corresponding BigInteger instance. *
   * A correctly formatted integer would have an optional sign as the first *
   * character (no sign means positive), and at least one digit character
   * (including zero).
   *
   * Examples of correct format, with corresponding values Format Value * +0 0 *
   * -0 0 * +123 123 * 1023 1023 * 0012 12 * 0 0 * -123 -123 * -001 -1 * +000 0 *
   * Leading and trailing spaces are ignored. So " +123 " will still parse *
   * correctly, as +123, after ignoring leading and trailing spaces in the input
   * string. * Spaces between digits are not ignored. So "12 345" will not parse
   * as * an integer - the input is incorrectly formatted. * An integer with value
   * 0 will correspond to a null (empty) list - see the BigInteger * constructor *
   *
   * @param integer Integer string that is to be parsed
   * @return BigInteger instance that stores the input integer.
   * @throws IllegalArgumentException If input is incorrectly formatted
   */
   public static BigInteger parse(String integer) throws IllegalArgumentException {
       integer = integer.trim();
       BigInteger bigInt = new BigInteger();
       int len;
       int i = 0;
       char c;
       DigitNode last = null;
       if (integer == null || integer.length() == 0) {
           throw new IllegalArgumentException("Please input a valid number");
       }
       len = integer.length();
       c = integer.charAt(0);
       if (c == '+')
           i++;
       else if (c == '-') {
           bigInt.negative = true;
           i++;
       }
       // ignore leading spaces after sign or leading 0
       while (i < len && (integer.charAt(i) == ' ' || integer.charAt(i) == '0')) {
           i++;
       }
       while (i < len) {
           c = integer.charAt(i);
           if (!Character.isDigit(c))
               throw new IllegalArgumentException("Please input a valid number. Invalid number " + integer);
           DigitNode n = new DigitNode(c - '0', null);
           if (bigInt.front == null) {
               bigInt.front = n;
           } else {
               last.next = n;
           }
           last = n;
           i++;
       }
       return bigInt;
   }
   /* IMPLEMENT THIS METHOD */ // following line is a placeholder for compilation return null; } /** * Adds the
                               // first and second big integers, and returns the result in a NEW BigInteger
                               // object. * DOES NOT MODIFY the input big integers. * * NOTE that either or
                               // both of the input big integers could be negative. * (Which means this method
                               // can effectively subtract as well.) * * @param first First big integer *
                               // @param second Second big integer * @return Result big integer */ public
                               // static BigInteger add(BigInteger first, BigInteger second) { /* IMPLEMENT
                               // THIS METHOD */ // following line is a placeholder for compilation return
                               // null; } /** * Returns the BigInteger obtained by multiplying the first big
                               // integer * with the second big integer * * This method DOES NOT MODIFY either
                               // of the input big integers * * @param first First big integer * @param second
                               // Second big integer * @return A new BigInteger which is the product of the
                               // first and second big integers */ public static BigInteger multiply(BigInteger
                               // first, BigInteger second) { /* IMPLEMENT THIS METHOD */ // following line is
                               // a placeholder for compilation return null; } /* (non-Javadoc) * @see
                               // java.lang.Object#toString() */

   public String toString() {
       if (front == null) {
           return "0";
       }
       String retval = front.digit + "";
       for (DigitNode curr = front.next; curr != null; curr = curr.next) {
           retval = retval + curr.digit ;
       }
       if (negative) {
           retval = '-' + retval;
       }
       return retval;
   }
}


Related Solutions

In C++, implement a class called setOper that provides several simple set operations. The class only...
In C++, implement a class called setOper that provides several simple set operations. The class only needs to deal with sets that are closed intervals specified by two real numbers; for example, the pair (2.5, 4.5) represent the interval [2.5, 4.5]. The following operations should be supported: - Check if the value x belongs to the given interval. - Check if the value x belongs to the intersection of two intervals. - Check if the value x belongs to the...
JAVA Specify, design, and implement a class called PayCalculator. The class should have at least the...
JAVA Specify, design, and implement a class called PayCalculator. The class should have at least the following instance variables: employee’s name reportID: this should be unique. The first reportID must have a value of 1000 and for each new reportID you should increment by 10. hourly wage Include a suitable collection of constructors, mutator methods, accessor methods, and toString method. Also, add methods to perform the following tasks: Compute yearly salary - both the gross pay and net pay Increase...
in JAVA: implement a class called tree (from scratch) please be simple so i can understand...
in JAVA: implement a class called tree (from scratch) please be simple so i can understand thanks! tree(root) node(value, leftchild,rightchild) method: insert(value)
ROCK, PAPER, SCISSORS Using C++, you will implement a class called Tool. It should have an...
ROCK, PAPER, SCISSORS Using C++, you will implement a class called Tool. It should have an int field called strength and a char field called type. You may make them either private or protected. The Tool class should also contain the function void setStrength(int), which sets the strength for the Tool. Create 3 more classes called Rock, Paper, and Scissors, which inherit from Tool. Each of these classes will need a default constructor that sets the strength to 1 and...
Hello, this question relates to a class I am taking called introduction to C++. I have...
Hello, this question relates to a class I am taking called introduction to C++. I have no experience writing programs and outside of learning out of a textbook, and studying on my own, have little understanding of logic. I have been assigned a problem that requires me to write a program for a Grocery Bill, where the consumer inputs the price for 5 items, that the program calculates the total with a 6% sales tax. I really am not sure...
Please in C++ I don't have the binarySearchTree (Carrano) Implement the code of the BinarySeachTree Class...
Please in C++ I don't have the binarySearchTree (Carrano) Implement the code of the BinarySeachTree Class to solve: (Gaddis) Programming Challenger 3. Car Class p. 802 Ch. 13 • Implement a menu of options • Add a motor vehicle to the tree • Remove a motor vehicle to the tree • Search by vehicle model • Vehicle Inventory Updates • Take one of the tours to verify the contents of the tree. Car Class Write a class named Car that...
I am in a class where I am supposed to be a Civil Society Organization Representative...
I am in a class where I am supposed to be a Civil Society Organization Representative (CSO) representing India. I was invited to the G20 meeting to discuss and present negotiations with other countries of G20.The agenda will have two major items: international health cooperation and international economic cooperation. What negotiations could I do for India with other countries to improve the current situation and look for financial stability?
I have GIS class. I want to do project, and I need to use ARCmap to...
I have GIS class. I want to do project, and I need to use ARCmap to search population of homeless at Denver Colorado. Can you help me to explain how to find the Population of homeless? Please
Overview For this assignment, implement and use the methods for a class called Seller that represents...
Overview For this assignment, implement and use the methods for a class called Seller that represents information about a salesperson. The Seller class Use the following class definition: class Seller { public: Seller(); Seller( const char [], const char[], const char [], double ); void print(); void setFirstName( const char [] ); void setLastName( const char [] ); void setID( const char [] ); void setSalesTotal( double ); double getSalesTotal(); private: char firstName[20]; char lastName[30]; char ID[7]; double salesTotal; };...
Overview For this assignment, implement and use the methods for a class called Seller that represents...
Overview For this assignment, implement and use the methods for a class called Seller that represents information about a salesperson. The Seller class Use the following class definition: class Seller { public: Seller(); Seller( const char [], const char[], const char [], double ); void print(); void setFirstName( const char [] ); void setLastName( const char [] ); void setID( const char [] ); void setSalesTotal( double ); double getSalesTotal(); private: char firstName[20]; char lastName[30]; char ID[7]; double salesTotal; };...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT