1. 程式人生 > >劍指offer——大數相乘問題(BigInteger的大致實現思路)

劍指offer——大數相乘問題(BigInteger的大致實現思路)

乘法運算可以分拆為兩步:第一步,是將乘數與被乘數逐位相乘;第二步,將逐位相乘得到的結果,對應相加起來。

public class BigInt {  
    public static void main(String[] args) {  
        Scanner sc = new Scanner(System.in);  
        String str1 = sc.next();  
        String str2 = sc.next();  
        int[] num1 = new int[str1.length()];  
        int
[] num2 = new int[str2.length()]; //把字串轉換成int陣列 for (int i = 0; i < str1.length(); i++) { num1[str1.length() - 1 - i] = str1.charAt(i) - '0'; } for (int i = 0; i < str2.length(); i++) { num2[str2.length() - 1 - i] = str2.charAt(i) - '0'
; } int[] result = multiply(num1, num2); // 因為前面做了倒序操作,所以最高位在最後 for (int i = result.length - 1; i >= 0; i--) { if(i==result.length - 1) if(result[i]==0) continue; System.out.print(result[i]); } sc.close(); } public
static int[] multiply(int[] num1, int[] num2) { int lengthOfNum1 = num1.length; int lengthOfNum2 = num2.length; //如果num1和num2的長度分別為n1,n2,那麼它們相乘的結果位數最大為n1+n2 int[] result = new int[lengthOfNum1 + lengthOfNum2]; //num[i]*num2[j]的結果存在result[i+j]上,最後再處理進位制問題 for (int i = 0; i < lengthOfNum1; i++) { for (int j = 0; j < lengthOfNum2; j++) { result[i + j] += num1[i] * num2[j]; } } // 處理進位制問題 for (int i = 0; i < lengthOfNum1 + lengthOfNum2 - 1; i++) { if (result[i] >= 10) { result[i + 1] += result[i] / 10; result[i] = result[i] % 10; } } return result; } }