1. 程式人生 > >leetcode 43 Multiply Strings 大數相乘

leetcode 43 Multiply Strings 大數相乘

length tco true 過程 urn class solution multipl pos

感覺是大數相乘算法裏面最能夠描述、模擬演算過程的思路

class Solution {
    public String multiply(String num1, String num2) {
        if(num1.charAt(0) == ‘0‘ || num2.charAt(0) == ‘0‘){
            return "0";
        }
        
        int len1 = num1.length();
        int len2 = num2.length();
        int len = len1+len2;
        int[] arr = new int[len];
        for(int i=len1-1;i>=0;i--){
            for(int j=len2-1;j>=0;j--){
                arr[i+j+1] += (num1.charAt(i)-‘0‘)*(num2.charAt(j)-‘0‘); 
            }
        }
        for(int i=len-1;i>0;i--){
            if(arr[i]>=10){
                arr[i-1] += arr[i]/10;
                arr[i]%=10;
            }
        }
        int i=0;
        if(arr[i] == 0) i++;
        String res = "";
        while(i<len){
            res = res+arr[i++];
        }
        return res;
    }
}

leetcode 43 Multiply Strings 大數相乘