php+math+biginteger,BigInteger类的概述和方法的使用(掌握)

BigInteger类的概述:可以让超过Integer范围内的数据进行运算

构造方法:

public BigInteger(String val)

成员方法:

public BigInteger add(BigInteger val)        加

public BigInteger subtract(BigInteger val) 减

public BigInteger multiply(BigInteger val) 乘

public BigInteger divide(BigInteger val)    除

public BigInteger[] divideAndRemainder(BigInteger val): 返回的是商和余数的数组

代码片段一:

//计算Integer的最大值

int maxValue = Integer.MAX_VALUE;

System.out.println("maxValue="+maxValue);

控制台打印:

c212583ce67e38b45681e54f758f4975.png

代码片段二:(超过范围)

public static void main( String[] args )

{

Integer integer = new Integer("2147483648");

System.out.println("integer="+integer);

}

控制台打印:

69142476bf71b00a47dfba9e41167de8.png

原因:超过了范围。

用法:

public static void main( String[] args )

{

System.out.println("---加法运算----");

BigInteger i1 = new BigInteger("10");

BigInteger i2 = new BigInteger("20");

System.out.println(i1.add(i2));

System.out.println("---减法运算----");

System.out.println(i1.subtract(i2));

System.out.println("---乘法运算----");

System.out.println(i1.multiply(i2));

System.out.println("---除法运算----");

System.out.println(i1.divide(i2));

BigInteger[] bigIntegers = i1.divideAndRemainder(i2);

for (BigInteger b: bigIntegers){

System.out.println("b="+b);

}

}

控制台打印结果:

c669e690559cff5a318425a5ab52a46d.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中的BigInteger类是用于处理大数的类。它可以处理比long类型更大的整数。BigInteger类的原理是使用一个int类型的数组来存储大数的每个位。数组中的每个元素都是大数的一部分。这个数组被称为mag[]。 1. 按位取反:BigInteger类提供了not()方法来实现按位取反的操作。该方法首先创建一个与原始BigInteger对象相同长度的int数组result[]。然后,通过循环遍历result[]数组,将mag[]数组中的每个元素取反并存储到result[]数组中。最后,使用valueOf()方法将result[]数组转换为一个新的BigInteger对象并返回。 示例代码如下: ```java public BigInteger not() { int[] result = new int[intLength()]; for (int i = 0; i < result.length; i++) { result[i] = ~getInt(result.length - i - 1); } return valueOf(result); } ``` 2. 按位与操作:BigInteger类提供了and()方法来实现按位与操作。该方法首先创建一个长度为两个BigInteger对象中较大的int数组result[]。然后,通过循环遍历result[]数组,将mag[]数组和另一个BigInteger对象的mag[]数组中对应位置的元素进行按位与操作,并将结果存储到result[]数组中。最后,使用valueOf()方法将result[]数组转换为一个新的BigInteger对象并返回。 示例代码如下: ```java public BigInteger and(BigInteger val) { int[] result = new int[Math.max(intLength(), val.intLength())]; for (int i = 0; i < result.length; i++) { result[i] = (getInt(result.length - i - 1) & val.getInt(result.length - i - 1)); } return valueOf(result); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值