Java实现两个大数相乘

<span style="font-size:18px;">import java.util.Scanner;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in = new Scanner(System.in);
		BigMulti bMulti = new BigMulti();
		String str1 = in.next();//next nextInt nextLine
		String str2 = in.next();//字符串,不识别无效字符
		int[] arr1 = bMulti.changeArr(str1);
		int[] arr2 = bMulti.changeArr(str2);
//		for(int i=0; i<arr1.length; i++){//测试用
//			System.out.print(arr1[i]+"\t");
//		}
//		for(int i=0; i<arr2.length; i++){
//			System.out.print(arr2[i]+"\t");		
//		}
		System.out.println(BigMulti.multiply(arr1, arr2));
//		StringBuffer sBuffer = new StringBuffer();
//		sBuffer.append("0");//stringbuffer 
//		sBuffer.append("3");
//		sBuffer.append("4");
//		System.out.println(sBuffer.toString());
	}

}
class BigMulti{
	public int[] changeArr(String str){
		int len = str.length();
		int[] arr = new int[len];
		for(int i=0; i<len; i++){
			arr[len-1-i] = Integer.parseInt(String.valueOf(str.charAt(i)));//string->char->string->int
		}
		return arr;
	}
	public static int multiply(int[] arr1, int[] arr2){
		int len1 = arr1.length;
		int len2 = arr2.length;
		int[] result = new int[len1+len2];
		for(int i=0; i<len1; i++){
			for(int j=0; j<len2; j++){
				int temp = result[i+j]+arr1[i]*arr2[j];
				result[i+j] = temp%10;
				result[i+j+1] += temp/10;
				if(result[i+j+1]>=10){
					result[i+j+1] %= 10;
					result[i+j+2]++;
				}
			}
		}
		StringBuffer sb = new StringBuffer();
//		for(int i=0; i<result.length; i++){
//			System.out.print(result[i]+"\t");
//		}
		System.out.print("@result0: "+result[0]+"\t");
		for(int i=result.length-1; i>=0; i--){
			sb.append(result[i]);
//			System.out.println("stringbuffer"+sb);
		}
		int res = Integer.parseInt(sb.toString());//0144转成整数后,自动去掉零
		return res;
	}
}</span>

点赞