大数相乘

两个大数相乘,

public class BigNumberMultiplication
{
	public static void main(String[] args)
	{
		//number1*number2
		String number1 = "3412522345234564578567856783652356239103489162389461293461923549125364785127834512345234523563456457645764562344523451234";
		String number2 = "12341235234536745764785678567634563454123412346192364923";
		long start = System.nanoTime();
		System.out.println(myMultiplication(number1,number2));
		long end = System.nanoTime();
		System.out.println(end - start);
	}
	
	public static String myMultiplication(String number1,String number2){
		
		StringBuffer result = new StringBuffer();//存放最终结果
		
		int number1Length = number1.length();//被乘数
		int number2Length = number2.length();//乘数
		
		char[] number1CharArray = number1.toCharArray();
		char[] number2CharArray = number2.toCharArray();
		int[] number1IntArray = new int[number1Length];
		int[] number2IntArray = new int[number2Length];
		
		for(int i=0;i<number1Length;i++){
			number1IntArray[i] = number1CharArray[i]-48;//将char的ascii转成对应的数字
		}
		
		for(int i=0;i<number2Length;i++){
			number2IntArray[i] = number2CharArray[i]-48;
		}
		
		int[] tempResult = new int[number1Length+1];//存入临时结果,每一次相乘结果最大比被乘数多一位
		
		for(int i=number2Length-1;i>=0;i--){
			
			int carry = 0;//进位
			
			for(int j=number1Length-1;j>=0;j--){
				int temp = number1IntArray[j]*number2IntArray[i]+carry+tempResult[j];
				carry = 0;
				if(temp>9){
					carry = temp/10;
				}
				tempResult[j+1] = temp%10;
			}
			
			tempResult[0] = carry;
			result.append(tempResult[number1Length]);
		}
		
		for(int i=tempResult.length-2;i>=0;i--){//最后一位己经加到结果中,剩下的才是需要的
			if(i==0&&tempResult[0]==0){
				continue;
			}
			result.append(tempResult[i]);
		}
		return result.reverse().toString();
	}
}
 

 

你可能感兴趣的:(大数相乘)