算法2-大数相乘

import java.io.*;


//数据类封装
class IntString {
	public int len;
	public int[] digits;

	public IntString() {
		len = 0;
		digits = null;
	}
}

//算法实现类
public class BigInt {
	public BigInt() {
	}

	public static void main(String[] args) throws java.io.IOException {
		System.out.println("Input two large integers:");
		
		IntString intt1 = new IntString();
		IntString intt2 = new IntString();
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		
		//通过空格实现字符串分段
		String str[] = (reader.readLine()).split("\\s+");
		intt1.digits = convert(str[0]);
		intt1.len = str[0].length();
		intt2.digits = convert(str[1]);
		intt2.len = str[1].length();
		int[] a = intt1.digits;
		int[] b = intt2.digits;
		int alength = intt1.len;
		int blength = intt2.len;
		
		IntString intt3 = new IntString();
		intt3.len = alength + blength - 1;
		int clength = intt3.len;
		int[] c = new int[1000];
		
		for (int i = 0; i < alength; i++)
			for (int j = 0; j < blength; j++)
				c[i + j] += a[i] * b[j];
		for (int i = 0; i < c.length; i++) {
			if (c[i] > 9) {
				c[i + 1] += c[i] / 10;
				c[i] = c[i] % 10;
			}
		}
		intt3.digits = c;
		clength = intt3.len;
		System.out.println(clength);
		System.out.println("the result is: ");
		for (int i = clength - 1; i >= 0; i--) {
			System.out.print(c[i]);
		}
	}

	//将字符串逆序
	public static int[] convert(String str) {
		int length = str.length();
		int[] tem = new int[length];
		for (int i = 0; i < str.length(); i++) {
			tem[i] = str.charAt(length - i - 1) - '0';
		}
		return tem;
	}
}

你可能感兴趣的:(算法)