在 Java中,有许多数字处理的类,比如Integer 类。但是Integer 类有一定的局限性,下面我们就来看看比 Integer 类更厉害的一个,BigInteger类。
BigInteger类型的数字范围较 Integer 类型的数字范围要大得多。我们都知道 Integer 是 Int 的包装类,int 的最大值为 231-1,如果要计算更大的数字,使用Integer 数据类型就无法实现了,所以 Java 中提供了BigInteger 类来处理更大的数字。 BigInteger 支持任意精度的整数,也就是说在运算中 BigInteger 类型可以准确地表示任何大小的整数值而不会丢失任何信息。
在 BigInteger类中封装了多种操作!除了基本的加减乘除操作之外,还提供了绝对值、相反数、最大公约数以及判断是否为质数等操作。
使用BigInteger 类,可以实例化一个BigInteger 对象,并自动调用相应的构造函数。BigInteger 类具有很多构造函数,但最直接的一种方式是参数以字符串形式代表要处理的数字。
语法如下:
|
1
|
public BigInteger(String val)
|
其中,val 是十进制字符串。
如果将 2 转换为 BigInteger 类型,可以使用以下语句进行初始化操作:
|
1
|
BigInteger twoInstance = new BigInteger ("2");
|
一旦创建了对象实例,就可以调用 BigInteger 类中的一些方法进行运算操作,包括基本的数学运算和位运算以及一些取相反数、取绝对值等操作。下面是 BigInteger 类几种常用的运算方法。
|
1
2
3
4
5
6
7
8
9
10
11
|
public BigInteger add(BigInteger val):做加法运算
public BigInteger subtract(BigInteger val):做减法运算
public BigInteger multiply(BigInteger val):做乘法运算
public BigInteger divide(BigInteger val):做除法运算
public BigInteger remainder(BigInteger val):做取余操作
public BigInteger pow(int exponet):进行取参数的 exponet 次方操作
public BigInteger negate():取相反数
public BigInteger shiftLegt(int n):将数字左移 n 位,如果 n 为负数,做右移操作
public BigInteger shiftRight(int n):将数字右移 n 位,如果 n 为负数,做左移操作
public int compareTo(BigInteger val):做数字比较操作
public BigInteger max(BigInteger val):返回较大的数值
|
下面是一个实例。在项目中创建一个类,在类的主方法中创建 BigInteger 类的实例对象,调用该对象的各种方法实现大整数的加减乘除和其他运算,并输出运行结果。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
public static void main(String[] args) {
BigInteger bigInstance = new BigInteger("4"); //实例化一个大数字
//取该大数字加2的操作
System.out.println("加法操作:"+
bigInstance.add(new BigInteger("2")));
//取该大数字减2的操作
System.out.println("减法操作:"+
bigInstance.subtract(new BigInteger("2")));
//取该大数字乘以2的操作
System.out.println("乘法操作:"+
bigInstance.multiply(new BigInteger("2")));
//取该大数字除以2的操作
System.out.println("除法操作:"+
bigInstance.divide(new BigInteger("2")));
//取该大数字除以3的商
System.out.println("取商:"+
bigInstance.divideAndRemainder(new BigInteger("3"))[0]);
//取该大数字除以3的余数
System.out.println("取余数:"+
bigInstance.divideAndRemainder(new BigInteger("3"))[1]);
//取该大数字的2次方
System.out.println("做2次方操作:"+
bigInstance.pow(2));
//取该大数字的相反数
System.out.println("取相反数操作:"+
bigInstance.negate());
}
}
|
以上就是关于 BigInteger 类的详解和实例分析,喜欢的朋友请继续关注快网idc。
相关文章
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
-
2025-06-04 96
-
2025-05-25 26
-
2025-05-25 76
-
2025-06-04 46
-
2025-05-27 108

