Java常用API(BigInteger)

在Java中,整数有四种类型:byte,short,int,long

在底层占用字节个数:byte 1个字节,short2个字节,int 4个字节,long 8个字节

对象一旦创建,里面的值是不能改变的。

1.随机获取一个最大整数

Random r = new Random();

for(int i = 0 ; i < 100 ; i ++){

BigInteger bd1 = new BigInteger(4,r);

System.out.println(bd1);[0~2^4-1]

}

2.获取一个指定的大整数 细节:字符串中必须是整数,否则会报错BigInteger bd2 = new BigInteger("1.1");System.out.println(bd2);

BigInteger bd3 = new BigInteger("abc");System.out.println(bd3);

3.获取指定进制的大整数

细节:

1.字符串中的数字必须是整数//2.字符串中的数字必须要跟进制吻合。//比如二进制中,那么只能写@和1,写其他的就报错。

BigInteger bd4 = new BigInteger("123",2)System.out.println(bd4);

4.静态方法获取BigInteger的对象,内部有优化细节:

1.能表示范围比较小,只能在1ong的取值范围之内,如果超出1ong的范围就不行了。

2.在内部对常用的数字:-16 ~ 16 进行了优化。提前把-16 ~ 16 先创建好BigInteger的对象,如果多次获取不会重新创建新的。

BigInteger bd5 = BigInteger.valueOf(16);BigInteger bd6= BigInteger.valueOf(16);

System.out.println(bd5 == bd6);//true

BigInteger bd7= BigInteger.valueOf(17);BigInteger bd8=BigInteger.valueOf(17);

System.out.println(bd7 == bd8);//false

方法小结

1.如果Big Integer表示的数字没有超出long的范围,可以用静态方法获取

2.如果Big Integer表示的超出long的范围,可以用构造方法获取

3.对象一旦创建,BigInteger内部记录的值就不会改变

4.只要进行计算都会产生一个新的BigInter对象

常用方法

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) 获取商除法

publicboolean equals(object x) 获取商和余数比较是否相同

publicBigInteger pow(int exponent) 次幂

publicBigInteger max/min(BigIntegerval) 返回较大值/较小值转为int类型整数

publicint intValue(BigInteger val) 超出范围数据有误

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值