java add(val)_Java BigInteger add方法

/*** 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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值