鏈家筆試題--java實現兩個大整數相乘的算法

兩個字符串表示兩個非常大的數,請設計算法計算這兩個大數的乘積,結果用字符串表示。例如S1=”7832974972840919321747983209327”,S2=”1987432091904327543957”,設計算法計算出S1*S2的結果,結果用String輸出,不準用BigInter。

思路:
根據手工計算兩數相乘的過程,用代碼實現這個過程。注意沒有考慮負數的情況。

代碼如下:

import java.util.Scanner;

/**
 * 兩個大整數相乘求結果返回字符串。
 * 
 * 
 */
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str1 = sc.nextLine();
        String str2 = sc.nextLine();
        String result = getResult(str1, str2);
        System.out.println(result);
    }

    private static String getResult(String str1, String str2) {
        // 求出兩個字符串的長度
        int n = str1.length();
        int m = str2.length();
        // 定義一個數組接收結果,長度一定不會超過n+m
        int num[] = new int[n + m];
        // 遍歷字符串的每一位,從後往前遍歷,然後計算結果
        for (int i = 0; i < n; i++) {
            // 遍歷每一位
            int a = str1.charAt(n - i - 1) - '0';
            // 定義一個進位
            int temp = 0;
            for (int j = 0; j < m; j++) {
                int b = str2.charAt(m - j - 1) - '0';
                // 計算 進位+num[i+j]+a*b
                temp = temp + num[i + j] + a * b;
                // 去餘 將個位存入數組中
                num[i + j] = temp % 10;
                // 保存進位
                temp = temp / 10;
            }
            // 第一輪循環結束,如果有進位,將進位放入更高的位置
            num[i + m] = temp;
        }
        // 計算結果到底是幾位數字
        int i = m + n - 1;
        while (i > 0 && num[i] == 0) {
            i--;
        }
        // 定義一個字符串 將數組反過來放入字符串中
        StringBuilder result = new StringBuilder();
        while (i >= 0) {
            result.append(num[i--]);
        }
        return result.toString();
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章