Java 大整数类型(BigInteger)

1. BigInteger

  • java.math.BigInteger 表示任意大小的整数
  • BigInteger 内部用一个int[]数组来模拟一个非常大的整数
public class BigInteger extends Number implements Comparable {
    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 

【信息由网络或者个人提供,如有涉及版权请联系COOY资源网邮箱处理】

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容