Java中提供了BigInteger 类。
BigInteger类型的数字范围较Integer,Long类型的数字范围要大得多,它支持任意精度的整数,也就是说在运算中
BigInteger 类型可以准确地表示任何大小的整数值而不会丢失任何信息。下面,让我们一起来学习一下BigInteger的常用方法:
读入方法
import java.math.BigInteger;
import java.util.Scanner;
public void test {
Scanner in=new Scanner(System.in);
//读入方法
BigInteger a=in.nextBigInteger();
System.out.println("a的值为: "+a);
}
构造方法
String str="10100110101";
BigInteger b=new BigInteger(str);//默认为十进制
System.out.println("b的值为: "+b);
BigInteger c=new BigInteger(str,2);//二进制
System.out.println("c的值为: "+c);
BigInteger d=new BigInteger(str,16);//十六进制
System.out.println("d的值为: "+d);
基本运算
返回值为BigInteger类型:add(),subtract(),multiply(),divide(),mod(),remainder(),pow(),abs(),negate();
//基本运算:add(),subtract(),multiply(),divide(),mod(),remainder(),pow(),abs(),negate()
public void testBasic() {
BigInteger a = new BigInteger("13");
BigInteger b = new BigInteger("4");
int n = 3;
//1.加
BigInteger bigNum1 = a.add(b); //17
//2.减
BigInteger bigNum2 = a.subtract(b); //9
//3.乘
BigInteger bigNum3 = a.multiply(b); //52
//4.除
BigInteger bigNum4 = a.divide(b); //3
//5.取模(需 b > 0,否则出现异常:ArithmeticException("BigInteger: modulus not positive"))
BigInteger bigNum5 = a.mod(b); //1
//6.求余
BigInteger bigNum6 = a.remainder(b); //1
//7.平方(需 n >= 0,否则出现异常:ArithmeticException("Negative exponent"))
BigInteger bigNum7 = a.pow(n); //2197
//8.取绝对值
BigInteger bigNum8 = a.abs(); //13
//9.取相反数
BigInteger bigNum9 = a.negate(); //-13
}
比较大小
compareTo()返回一个int型数据:1 大于; 0 等于; -1 小于;
max(),min():分别返回大的(小的)那个BigInteger数据;
//比较大小:compareTo(),max(),min()
public void testCompare() {
BigInteger bigNum1 = new BigInteger("52");
BigInteger bigNum2 = new BigInteger("27");
//1.compareTo():返回一个int型数据(1 大于; 0 等于; -1 小于)
int num = bigNum1.compareTo(bigNum2); //1
//2.max():直接返回大的那个数,类型为BigInteger
// 原理:return (compareTo(val) > 0 ? this : val);
BigInteger compareMax = bigNum1.max(bigNum2); //52
//3.min():直接返回小的那个数,类型为BigInteger
// 原理:return (compareTo(val) < 0 ? this : val);
BigInteger compareMin = bigNum1.min(bigNum2); //27
}
## 常量
ZERO,ONE,TEN 返回值为BigInteger类型:有朋友提到的-1,2,源码注释里面已表明不再输出(Not exported.);
```java
//常量(返回BigInteger类型)
//有朋友提到的-1和2,源码注释里面已表明不再输出(Not exported.)
public void testFinalNum() {
//0
BigInteger zero = BigInteger.ZERO;
//1
BigInteger one = BigInteger.ONE;
//10
BigInteger ten = BigInteger.TEN;
}
类型转换
将BigInteger数据转换成基本数据类型,还可以转换成radix进制的字符串形式;
//类型转换(返回类型如下)
@Test
public void testToAnother() {
BigInteger bigNum = new BigInteger("52");
int radix = 2;
//1.转换为bigNum的二进制补码形式
byte[] num1 = bigNum.toByteArray();
//2.转换为bigNum的十进制字符串形式
String num2 = bigNum.toString(); //52
//3.转换为bigNum的radix进制字符串形式
String num3 = bigNum.toString(radix); //110100
//4.将bigNum转换为int
int num4 = bigNum.intValue();
//5.将bigNum转换为long
long num5 = bigNum.longValue();
//6.将bigNum转换为float
float num6 = bigNum.floatValue();
//7.将bigNum转换为double
double num7 = bigNum.doubleValue();
}