超大整数计算
ava中long类型可以表示 -9,223,372,036,854,775,808(即-2^64)到9,223,372,036,854,775,807(即2^64-1)范围内的整数。有的时候我们希望能够处理在此范围之外的整数。为此,我们设计了一个BigInteger类。它可以支持大整数的加、减、乘操作。请根据提供的代码框架,完成整个程序。
> 注:
> 1) 请仔细阅读代码中的注释,并在标有// YOU FILL THIS IN 的位置添加你的代码。你可以添加自己的方法、变量,但是请不要修改已有的代码。
public class BigInteger {
// The sign of this integer - true for a positive number, and false
// otherwise
private boolean sign = true;
// digits[0] is the most significant digit of the integer, and
// the last element of this array is the least significant digit.
// For example, if we have a BigInteger of value 34, then
// digits[0] = 3 and digits[1] = 4.
private byte[] digits;
public BigInteger() {
this.digits = new byte[1];
this.digits[0] = 0;
}
public BigInteger(byte[] digits) {
this.digits = digits;
}
/**
* Initializes a <code>BigInteger</code> according to a string. The form of
* <code>numberStr</code> is a string consisting of all digits ranging from
* 0 to 9, following an OPTIONAL minus symbol (i.e., "-"). For example,
* "1234567891234567" and "-17788399934334388347734" are both valid.
*
* @param numberStr
* a number expressed as a string
*/
public BigInteger(String numberStr) {
// YOU FILL THIS IN
// Note: You should parse the string and initialize the "digits" array
// properly.
// You may also need to set the "sign" variable to a correct value.
}
/**
* Performs addition.
*
* @param another
* another <code>BigInteger</code> object
* @return this+another
*/
public BigInteger add(BigInteger another) {
// YOU FILL THIS IN
}
/**
* Performs addition.
*
* @param num
* an integer
* @return this+num
*/
public BigInteger add(int num) {
// YOU FILL THIS IN
}
/**
* Performs subtraction.
*
* @param another
* another <code>BigInteger</code> object
* @return this-another
*/
public BigInteger subtract(BigInteger another) {
// YOU FILL THIS IN
}
/**
* Performs subtraction.
*
* @param num
* an integer
* @return this-num
*/
public BigInteger subtract(int num) {
// YOU FILL THIS IN
}
/**
* Performs multiplication.
*
* @param another
* another <code>BigInteger</code> object
* @return this*another
*/
public BigInteger multiply(BigInteger another) {
// YOU FILL THIS IN
}
/**
* Performs multiplication.
*
* @param num
* an integer
* @return this*num
*/
public BigInteger multiply(int num) {
// YOU FILL THIS IN
}
public String toString() {
StringBuffer buf = new StringBuffer();
if (!sign) {
buf.append("-");
}
for (byte d : digits) {
buf.append(d);
}
return buf.toString();
}
public static void main(String[] args) {
BigInteger i1 = new BigInteger("999999999999999999");
BigInteger i2 = i1.add(1);
System.out.println(i2); // the output should be 1000000000000000000
BigInteger i3 = i2.multiply(i1);
System.out.println(i3); // expected: 999999999999999999000000000000000000
System.out.println(i3.subtract(-3)); // expected: 999999999999999999000000000000000003
}
}
急!!!