Detailed explanation of how to use the BigInteger class in Java, the most commonly used series!

Original blog posts are welcome to be reprinted. Please be sure to include a link to the blog post when reprinting. Thank you for your respect.

In Java, there are many number processing classes, such as the Integer class, but the Integer class has certain limitations.

We all know that Integer is a wrapper class of Int, and the maximum value of int is 2^31-1. If you want to describe larger integer data, it cannot be achieved using the Integer data type, so the BigInteger class is provided in Java.

The number range of the BigInteger type is much larger than that of the Integer and Long types. It supports arbitrary-precision integers, which means that the BigInteger type can accurately represent integer values ​​of any size during operations without losing any information.

Next, let us learn the common methods of BigInteger:

text:

Reading method

nextBigInteger(): The console reads a BigInteger type data, similar to the int type nextInt();

	//读入方法:nextBigInteger()
	@Test
	public void test5() {
    
    
		Scanner scan = new Scanner(System.in);				// 读入
		int n = scan.nextInt(); 							// 读入一个int;
		BigInteger m = scan.nextBigInteger();				// 读入一个BigInteger;
		while(scan.hasNext()){
    
    	
			System.out.print("scan.hasNext()=" + scan.hasNext());
		}
	}
Construction method

The default is decimal, which is also the most commonly used one. It also supports custom decimal types (existing ones);

	//进制转换
	@Test
	public void testScale() {
    
    
		//在构造将函数时,把radix进制的字符串转化为BigInteger
		String str = "1011100111";
		int radix = 2;
		BigInteger interNum1 = new BigInteger(str,radix);	//743

		//我们通常不写,则是默认成10进制转换,如下:
		BigInteger interNum2 = new BigInteger(str);			//1011100111
	}
Basic operations

The return value is of BigInteger type: add(), subtract(), multiply(), divide(), mod(), remainder(), pow(), abs(), negate();

	//基本运算:add(),subtract(),multiply(),divide(),mod(),remainder(),pow(),abs(),negate()
	@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
	}
Comparison of size

compareTo() returns an int type data: 1 is greater than; 0 is equal to; -1 is less than;
max(), min(): return the larger (smaller) BigInteger data respectively;

	//比较大小: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
	}
constant

The return value of ZERO, ONE, TEN is of BigInteger type: -1, 2 as mentioned by a friend. The source code comments indicate that it will no longer be output (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;
	}
type conversion

Convert BigInteger data into basic data types, and also into radix string form;

	//类型转换(返回类型如下)
	@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();
	}
Binary operations

The return value is of BigInteger type. This type of method is not commonly used, so be prepared;

	//二进制运算(返回类型都为BigInteger,不常用,但有备无患)
	@Test
	public void testBinaryOperation() {
    
    
		BigInteger a = new BigInteger("13");
		BigInteger b = new BigInteger("2");
		int n = 1;

		//1.与:a&b
		BigInteger bigNum1 = a.and(b);			//0
		//2.或:a|b
		BigInteger bigNum2 = a.or(b);			//15
		//3.异或:a^b
		BigInteger bigNum3 = a.xor(b);			//15
		//4.取反:~a
		BigInteger bigNum4 = a.not();			//-14
		//5.左移n位: (a << n)
		BigInteger bigNum5 = a.shiftLeft(n);	//26
		//6.右移n位: (a >> n)
		BigInteger bigNum6 = a.shiftRight(n);	//6
	}
Permission control

setBit(), testBit(): can be used for menu permission control, very easy to use, the principle is as follows:

	//权限控制:setBit(),testBit()
	@Test
	public void testSetAndTest() {
    
    
		//1.封装数据(setBit的值需 >= 0,否则出现异常:ArithmeticException("Negative bit address"))
		BigInteger permission = new BigInteger("0");
		BigInteger numBig = permission.setBit(2);
		numBig = numBig.setBit(5);
		numBig = numBig.setBit(13);
		numBig = numBig.setBit(66);
		System.out.println("原理:" + numBig);	
		// 原理:73786976294838214692 = 2^2+2^5+2^13+2^66 次方的和;
		// 看!!即使这么大的数也不会溢出,而int最大值只有2147483647;

		//2.取值验证(返回Boolean型)
		boolean flag1 = numBig.testBit(2);		//true
		boolean flag2 = numBig.testBit(5);		//true
		boolean flag3 = numBig.testBit(13);		//true
		boolean flag4 = numBig.testBit(66);		//true
		boolean flag5 = numBig.testBit(27);		//false
	}
Source code analysis

setBit(): Treat the set variables as binary numbers, calculate their sum, and display it in decimal;
testBit(): Contrary to setBit(), verify whether the binary component element of this contains the incoming variable;

	//权限控制源码分析:
	
	//1.setBit()原理:计算this与2的n次方的和
	public BigInteger setBit(int n) {
    
    
		if (n < 0)
			throw new ArithmeticException("Negative bit address");

		int intNum = n >>> 5;
		int[] result = new int[Math.max(intLength(), intNum+2)];

		for (int i=0; i < result.length; i++)
			result[result.length-i-1] = getInt(i);

		result[result.length-intNum-1] |= (1 << (n & 31));

		return valueOf(result);
	}
	
	//2.testBit()原理:计算this的值中是否包含2的n次方
	public boolean testBit(int n) {
    
    
		if (n < 0)
			throw new ArithmeticException("Negative bit address");

		return (getInt(n >>> 5) & (1 << (n & 31))) != 0;
	}

summary

  1. BigInteger is also immutable, and a new object will be generated during each operation. A new object will be generated. When an abnormal arithmetic condition occurs, an ArithmeticException is thrown. For example, dividing an integer by "0" will throw an instance of this class;
  2. Suppose there is a problem of calculating the square of an int data with the size of another, it is likely to cause memory overflow. In addition to using the dichotomy method, using the compareTo method of BigInteger is also a good choice, it is simple and easy to understand, and does not require algorithm support;
  3. This chapter is used as a note, and the content is relatively comprehensive, but the commonly used ones are only: constructors, basic operations and compareTo(), intValue(), setBit(), testBit() methods;
  4. The setBit() and testBit() methods can be used to control the permissions of the menu. The editor has tried it many times during development and it is very easy to use. Many Weibo have related introductions, so I won’t do a project demonstration here.

I am an IT ignorant man. Your likes, comments and attention are my unremitting motivation to continue creating.
There is no end to learning, and there is great energy. Let us work hard together, ride the wind and waves, and see you again in the world! !

Supongo que te gusta

Origin blog.csdn.net/weixin_44259720/article/details/87002816
Recomendado
Clasificación