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) 超出范围数据有误
了解更多跨境独立站电商代购系统和国内外电商API,可以私信或评论区交流 ,感谢你的关注。
END
云服务器活动(最新)
扫码添加站长好友
文章投稿、业务合作、咨询等
技术交流、问题反馈等