Java 大整数类型(BigInteger)

2023-12-28  本文已影响0人  Tinyspot

1. BigInteger

public class BigInteger extends Number implements Comparable<BigInteger> {
    final int[] mag;
}

2. 示例

@Test
public void demo() {
    BigInteger bi = new BigInteger("123456789");
    System.out.println(bi.pow(5));

    BigInteger bi1 = new BigInteger("123456789");
    BigInteger bi2 = new BigInteger("12345678987654321");
    System.out.println(bi1.add(bi2));
}

3. 类型转换

@Test
public void longValue() {
    BigInteger bi = new BigInteger("123456789000");
    System.out.println(bi.multiply(bi).longValue());

    // BigInteger out of long range
    System.out.println(bi.multiply(bi).longValueExact());
}

longValueExact() 如果超出了long型的范围,会抛出ArithmeticException

public long longValueExact() {
    if (mag.length <= 2 && bitLength() <= 63)
        return longValue();
    else
        throw new ArithmeticException("BigInteger out of long range");
}
上一篇 下一篇

猜你喜欢

热点阅读