/*** Returns a BigInteger whose value is {@code(this + val)}.
*
*@paramval value to be added to this BigInteger.
*@return{@codethis + val}*/
publicBigInteger add(BigInteger val) {if (val.signum == 0)return this;if (signum == 0)returnval;if (val.signum ==signum)return newBigInteger(add(mag, val.mag), signum);int cmp =compareMagnitude(val);if (cmp == 0)returnZERO;int[] resultMag = (cmp > 0 ?subtract(mag, val.mag)
: subtract(val.mag, mag));
resultMag=trustedStripLeadingZeroInts(resultMag);return new BigInteger(resultMag, cmp == signum ? 1 : -1);
}
/**
* Adds the contents of the int arrays x and y. This method allocates
* a new int array to hold the answer and returns a reference to that
* array.
*/
private static int[] add(int[] x, int[] y) {
// If x is shorter, swap the two arrays
if (x.length < y.length) {
int[] tmp = x;
x = y;
y = tmp;
}
int xIndex = x.length;
int yIndex = y.length;
int result[] = new int[xIndex];
long sum = 0;
if (yIndex == 1) {
sum = (x[--xIndex] & LONG_MASK) + (y[0] & LONG_MASK) ;
result[xIndex] = (int)sum;
} else {
// Add common parts of both numbers
while (yIndex > 0) {
sum = (x[--xIndex] & LONG_MASK) +
(y[--yIndex] & LONG_MASK) + (sum >>> 32);
result[xIndex] = (int)sum;
}
}
// Copy remainder of longer number while carry propagation is required
boolean carry = (sum >>> 32 != 0);
while (xIndex > 0 && carry)
carry = ((result[--xIndex] = x[xIndex] + 1) == 0);
// Copy remainder of longer number
while (xIndex > 0)
result[--xIndex] = x[xIndex];
// Grow result if necessary
if (carry) {
int bigger[] = new int[result.length + 1];
System.arraycopy(result, 0, bigger, 1, result.length);
bigger[0] = 0x01;
return bigger;
}
return result;
}