(1)用Java内部实现的BigInteger里面的函数multiply();
Scanner sc=new Scanner(System.in);
String s1=sc.nextLine();
String s2=sc.nextLine();
BigInteger a =new BigInteger(s1);
BigInteger b =new BigInteger(s2);
BigInteger c=a.multiply(b);
(2)基于平时计算乘法的步骤,用map存储每个位相乘后的结果。
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String s1=sc.nextLine();
String s2=sc.nextLine();
Map<Integer,Integer> n1=new HashMap<Integer,Integer>();//存放第一个
Map<Integer,Integer> n2=new HashMap<Integer,Integer>();//存放第二个
Map<Integer,Integer> result=new HashMap<Integer,Integer>();//存放结果
//将s1和s2放到n1和n2中
n1=makeBigInteger(s1);
n2=makeBigInteger(s2);
//将两个计算
result= mult(n1,n2);
//算出结果
System.out.println(getResult(result));
}
//该函数将高位和低位分别存到key和value中
public static Map<Integer,Integer> makeBigInteger(String s){
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
int len=s.length();
for(int i=1;i<=s.length();++i){
map.put(len--,Integer.parseInt(s.substring(i-1,i)));
}
return map;
}
//将两个大数map进行相乘
public static Map<Integer,Integer> mult(Map<Integer,Integer> p1,Map<Integer,Integer> p2){
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int j=1;j<=p1.size()+p2.size();++j){
map.put(j,0);
}
for(int i=1;i<=p1.size();++i){
for(int k=1;k<=p2.size();++k){
int num=k+i-1; //就是位数,个位数,十位数,百位数...
int result=p1.get(i) * p2.get(k); //获取相乘的结果
if(result/10==0){
add(num,result,map);//未进位处理
}else {
add(num,result%10,map);//将余数写入当前位数
add(num+1,result/10,map);//将进位的数写入上一个位数,并且存入map
}
}
}
return map;
}
//解决数字相加后大于9的进位问题
public static void add(int num,int result,Map<Integer,Integer> map){
int r=map.get(num)+result;//该map 是新生的map,value全是0
if(r/10==0){ //未进位,直接放进去
map.put(num,r);
}else{ //进位
map.put(num,r%10); //将进位的余数写入当前位数
add(num+1,r/10,map); //将进位的数写入上一个位数,并且存入map
}
}
//将result的map转化为String输出
public static String getResult(Map<Integer,Integer> map){
String result="";
for(int i= map.size(); i>=1;i--){
if(map.get(i) == 0 && result.equals("")){}
else{
result += map.get(i) + "";
}
}
return result;
}
}