BigInteger类的使用以及常用方法

BigInteger类

在刷算法题的时候,经常会遇到一些大数的高精度问题,使用Integer,Long类型不能完全通过题目的数据范围。Java中提供了BigInteger 类。BigInteger类型的数字范围相较Integer,Long类型的数字范围要大得多,它支持任意精度的整数,也就是说在运算中 BigInteger 类型可以准确地表示任何大小的整数值而不会丢失任何信息。

1.读入方法
Scanner in = new Scanner(System.in);				// 读入
int n = in.nextInt(); 						// 读入一个int;
BigInteger m1 = BigInteger.valueOf(n);                          // 再使用valueOf()方法
BigInteger m2 = in.nextBigInteger();				// 读入一个BigInteger;
2.构造方法
//进制转换
public void testScale() {
	//在构造将函数时,把radix进制的字符串转化为BigInteger
	String str = "1011100111";
	int radix = 2;
	BigInteger interNum1 = new BigInteger(str,radix);	//将str按二进制转换为743

	//我们通常不写,则是默认成10进制转换,如下:
	BigInteger interNum2 = new BigInteger(str);			//1011100111
}
3.基本运算

返回值为BigInteger类型:add(),subtract(),multiply(),divide(),mod(),remainder(),pow(),abs(),negate(),gcd();
在众多关于BigInteger中,甚至提供了封装好的求最大公约数的方法gcd(),就是这么的方便和无赖

//基本运算:add(),subtract(),multiply(),divide(),mod(),remainder(),pow(),abs(),negate(),gcd()
@Test
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
    //10.求最大公约数
    BigInteger bigNum10 = c.gcd(d)			//c=30,d=50,bigNum10=10
}
4.比较大小

compareTo()返回一个int型数据:1 大于; 0 等于; -1 小于;
max(),min():分别返回大的(小的)那个BigInteger数据;

//比较大小:compareTo(),max(),min()
@Test
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
}
5.常量

ZERO,ONE,TEN 返回值为BigInteger类型:有朋友提到的-1,2,源码注释里面已表明不再输1出(Not exported.);

//常量(返回BigInteger类型)
//有朋友提到的-1和2,源码注释里面已表明不再输出(Not exported.)
@Test
public void testFinalNum() {
	//0
	BigInteger zero = BigInteger.ZERO;
	//1
	BigInteger one = BigInteger.ONE;
	//10
	BigInteger ten = BigInteger.TEN;
}
posted @ 2021-04-08 23:36  霄大宝  阅读(1399)  评论(0)    收藏  举报
Live2D