We need to know that programs sometimes need to deal with large integers , so what should we do? We can use the BigInteger class in the java.math package to provide arbitrary precision integer operations by constructing a decimal BigInteger object using the construction method public BigInteger(String val).
This constructor can generate a NumberFormatException exception . That is to say, if the string parameter val contains non-numeric characters, a NumberFormatException exception will occur.
Commonly used methods of the BigInteger class are as follows:
Returns the sum of the current large integer object and the large integer object specified by the parameter.
Returns the difference between the current large integer object and the large integer object specified by the parameter.
Returns the product of the current large integer object and the large integer object specified by the parameter.
Returns the quotient of the current large integer object and the large integer object specified by the parameter.
Returns the remainder of the current large integer object and the large integer object specified by the parameter.
Returns the comparison result between the current large integer object and the large integer specified by the parameter. The return value is 1, -1 or 0, which respectively indicates that the current large integer object is greater than, less than or equal to the large integer specified by the parameter.
Returns the absolute value of the current large integer object.
Returns the current large integer object raised to the power a.
Returns the decimal string representation of the current large integer object.
Returns the p-base string representation of the current large integer object.
Let's look at a method of using the large integer class. Let's take the question of adding large numbers as an example. It requires calculating the sum of a + b. However, this question clearly states that the two numbers a and b do not exceed 1000 digits. You can think of it As we know, general plastic surgery will definitely not fit in. The addition of 1000-digit numbers is billions. However, the conventional method is to store numbers in arrays and simulate operations such as addition and carry, which is more troublesome to operate. And if you use Java's large integer class, the code is very simple, as follows:
importjava.math.BigInteger;importjava.util.Scanner;publicclassMain{publicstaticvoidmain(String[]args){Scannersc=newScanner(System.in);BigIntegera=sc.nextBigInteger();BigIntegerb=sc.nextBigInteger();System.out .println(a.add(b));}}
You can test it on your own computer and complete it.
Compared with other languages, such as C and C++, the speed of solving problems is really fast.