Big integer multiplication is actually very simple (Java)
Purpose and introduction
Use Java language to achieve large integer multiplication
As long as the big integers are multiplied, the addition, subtraction and division of big integers are very simple
Add large integers, only need a loop for carry operation
Subtract large integers, only need to borrow in the loop, pay attention to the sign.
Dividing large integers is simply subtracting large integers multiple times.
Design ideas
Simulate mathematical multiplication, multiply by bit, and add at the end
When adding, if the low bit exceeds 10, move forward
Specific steps
The operator is judged first, and the final result is positive or negative.
Manual operations can be forwarded, but the computer performs string inversion, which is convenient for calculation and storage
For the result of the calculation, you need to find a place to store it. The size of the new array is the number of digits of the product of the two numbers, which will not be greater than the sum of the two digits.
Perform calculations and numerical processing (carry)
Remember to remove the extra 0, and bring the sign
Code
publicclassBigIntegersMulti{
//大整数乘法public String multi(String args, String args2){
StringBuffer sb =newStringBuffer(args);
StringBuffer sb2 =newStringBuffer(args2);//运算符判断int signal =0;if("-".equals(args.substring(0,1))){
sb.delete(0,1);
signal++;}if("-".equals(args2.substring(0,1))){
sb2.delete(0,1);
signal++;}//字符串逆置,方便计算和存储char[] ch = sb.reverse().toString().toCharArray();char[] ch2 = sb2.reverse().toString().toCharArray();//两个数相乘的积位数不会大于两数位数之和int length = ch.length + ch2.length;int[] sum =newint[length];//运算for(int i =0; i < ch.length; i++){
for(int j =0; j < ch2.length; j++){
sum[i + j]+=(ch[i]-'0')*(ch2[j]-'0');}}//数值整理和进位for(int i =0; i < length -1; i++){
sum[i +1]+=(sum[i]/10);
sum[i]%=10;}
StringBuffer sb3 =newStringBuffer();//消除0,比如000123,应该输出123int u = length -1;while(sum[u]==0){
u--;}//逆序for(; u >=0; u--){
sb3.append(sum[u]);}//带上运算符号if((signal &1)==1){
sb3.insert(0,"-");}return sb3.toString();}}
Test case design
Test negative number multiplied by negative number
Test positive numbers multiplied by negative numbers
By 99 99,9999 give multiples of 9999 9 mathematical relationship, for multiplying the number of authentication (two identical 9 composed of the n, the result is the n-1 9 8 plus one plus the n-1 0 plus a 1)