In: Computer Science
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 + "";
}
}
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;
}
}