大數相乘

大數乘法[JAVA實現]-經典筆試題

package com.company;

import java.util.Scanner;

/**
 * 大數相乘
 * @author Ant
 *
 */
public class BigNumMutil {

    /**
     * 大數相乘基本思想,輸入字符串,轉成char數組,轉成int數組。採用分治思想,每一位的相乘;<br>
     * 公式:AB*CD = AC (BC+AD) BD , 然後從後到前滿十進位(BD,(BC+AD),AC)。
     * @param num1
     * @param num2
     */
    public String multiply(String num1, String num2){
        //把字符串轉換成char數組
        char chars1[] = num1.toCharArray();
        char chars2[] = num2.toCharArray();

        //聲明存放結果和兩個乘積的容器
        int result[] = new int[chars1.length + chars2.length];
        int n1[] = new int[chars1.length];
        int n2[] = new int[chars2.length];

        //把char轉換成int數組,爲什麼要減去一個'0'呢?因爲要減去0的ascii碼得到的就是實際的數字
        for(int i = 0; i < chars1.length;i++)
            n1[i] = chars1[i]-'0';
        for(int i = 0; i < chars2.length;i++)
            n2[i] = chars2[i]-'0';

        //逐個相乘,因爲你會發現。AB*CD = AC(BC+AD)BD , 然後進位。
        for(int i =0 ; i < chars1.length; i++){
            for(int j =0; j < chars2.length; j++){
                result[i+j]+=n1[i]*n2[j];
            }
        }

        //滿10進位,從後往前滿十進位
        for(int i =result.length-1; i > 0 ;i--){
            result[i-1] += result[i] / 10;
            result[i] = result[i] % 10;
        }

        //轉成string並返回
        String resultStr = "";
        for(int i = 0; i < result.length-1; i++){
            resultStr+=""+result[i];
        }
        return resultStr;
    }

    public static void main(String[] args) {
        BigNumMutil bm = new BigNumMutil();
        System.out.println("-----輸入兩個大數------");
        Scanner scanner = new Scanner(System.in);
        String num1 = scanner.next();
        String num2 = scanner.next();
        String result = bm.multiply(num1, num2);
        System.out.println("相乘結果爲:"+result);
        scanner.close();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章