leetcode 43. 字符串相乘 擊敗83%

給定兩個以字符串形式表示的非負整數 num1 和 num2,返回 num1 和 num2 的乘積,它們的乘積也表示爲字符串形式。

示例 1:

輸入: num1 = “2”, num2 = “3” 輸出: “6” 示例 2:

輸入: num1 = “123”, num2 = “456” 輸出: “56088” 說明:

num1 和 num2 的長度小於110。 num1 和 num2 只包含數字 0-9。 num1 和 num2 均不以零開頭,除非是數字
0 本身。 不能使用任何標準庫的大數類型(比如 BigInteger)或直接將輸入轉換爲整數來處理。

	//思路就是逐位相乘,得到的乘積可以通過兩個數字分別所在位置判斷他們乘積所在位置,將得到的乘積與該結果位已有數相加即可
    public static String multiply(String num1, String num2) {
        if ("0".equals(num1) || "0".equals(num2)) {
            return "0";
        }
        //讓num1乘以num2的每一位
        if (num1.length() < num2.length()) {
            return multiply(num2, num1);
        }
        int[] res = new int[num1.length() + num2.length()];
        for (int i = num2.length() - 1; i >= 0; i--) {
            for (int j = num1.length() - 1; j >= 0; j--) {
                //i+j+1位置可能之前已經有值,所以乘當前之後還要加上原來的
                int temp = (num1.charAt(j) - '0') * (num2.charAt(i) - '0') + res[i + j + 1];
                res[i + j + 1] = temp % 10;
                //然後將進位給到前一位
                res[i + j] += temp / 10;
            }
        }
        StringBuilder result = new StringBuilder();
        //數組首位可能是0,比如123*456=056088
        if(res[0]!=0){
            result.append(res[0]);
        }
        for (int i = 1; i < res.length; i++) {
            result.append(res[i]);
        }
        return result.toString();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章