java简单实现大数相乘

面试的一道题 ,让我实现大数相乘的算法,晕倒。

 

 

package test;

import java.math.BigInteger;

public class BigNumberHandler {

	public int[] a = new int[100];

	public int[] b = new int[100];

	public BigNumberHandler() {
		initData(a);
		initData(b);
		print(a);
		print(b);
	}

	private void initData(int[] t) {
		for (int i = 0; i < t.length; i++) {
			t[i] = (int) (Math.random() * 10);
		}
	}

	private void print(int[] t) {
		for (int i = 0; i < t.length; i++) {
			System.out.print(t[t.length - i - 1]);
		}
		System.out.println("");
	}

	public void process() {

		int[] result = new int[a.length + b.length];
		
		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < b.length; j++) {
				int number = b[j] * a[i];
				int index = i + j;
				result[index] += number;
			}
		}

		for (int i = 0; i < result.length - 1; i++) {
			int t = result[i];
			if (t > 9) {
				result[i + 1] += t / 10;
				result[i] = t - t / 10 * 10;
			}

		}

		print(result);

	}

	public static String getString(int[] t) {
		StringBuffer sBuffer = new StringBuffer();
		for (int i = 0; i < t.length; i++) {
			sBuffer.append(t[t.length - i - 1]);
		}
		return sBuffer.toString();
	}

	public static void main(String[] args) {
		BigNumberHandler t = new BigNumberHandler();
		t.process();
		
		
		BigInteger a = new BigInteger(getString(t.a));
		BigInteger b = new BigInteger(getString(t.b));
		System.out.println(a);
		System.out.println(b);

		System.out.println(a.multiply(b));
	}

}

 

你可能感兴趣的:(java)