题目
数组模拟乘法运算
数据范围1~3e30
注释
- @Title 大数乘法.java
- @author Baisu
- @date 2019年10月29日
- @version 1.0
说明
版本1.0,还没开始优化,后续可能会优化代码
源代码
package 大数运算;
import java.util.*;
/**
* @Title 大数乘法.java
* @author Baisu
* @date 2019年10月29日
* @version 1.0
*/
public class 大数乘法 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//声明字符串变量
String s1 = new String();
String s2 = new String();
//输入大数字符串
s1 = sc.nextLine();
s2 = sc.nextLine();
//字符串存储到数组
char c1[] =s1.toCharArray();
char c2[] =s2.toCharArray();
//声明整型数组变量
int a1 [] = new int [60];
int a2 [] = new int [60];
//字符数组转化为整数数组
for(int i=0; i<c1.length; i++) {
a1[c1.length-i-1] = c1[i];
a1[c1.length-i-1]-=48;
}
for(int i=0; i<c2.length; i++) {
a2[c2.length-i-1] = c2[i];
a2[c2.length-i-1]-=48;
}
//声明整型数组存储结果
int a3 [] = new int [100];
//计算结果
for(int i=0; i<40; i++) {
for(int j=0; j<40; j++) {
a3[j+i] += a1[i] * a2[j];
}
}
//修正结果
for(int i=0; i<40; i++) {
if(a3[i]>=10) {
a3[i+1]+=a3[i]/10;
a3[i]%=10;
}
}
//输出结果
int b = 0;
for(int i=99; i>=0; i--) {
if(a3[i]!=0) {
b=i;
break;
}
}
for(int i=b; i>=0; i--) {
System.out.print(a3[i]);
}
}
}