1218-2019-LEETCODE-43- corda multiplicado

Solução Fonte:
https://leetcode-cn.com/problems/multiply-strings/solution/you-hua-ban-shu-shi-da-bai-994-by-breezean/

public String multiply(String num1, String num2) {
        if (num1.equals("0") || num2.equals("0")){
            return "0";
        }
        //保证字符串更长的作为被乘数。
        if (num1.length() < num2.length()){
            String s = num1;
            num1 = num2;
            num2 = s;
        }
        String res = "0";
        for (int i = num2.length() - 1; i >= 0 ; i--) {
            int carry = 0;//保存进位。
            StringBuilder temp = new StringBuilder();
            //按位补0
            for (int j = 0; j < num2.length() - i - 1; j++) {
                temp.append("0");
            }
            int m1 = num2.charAt(i) - '0';
            //按num1与num2的第i位相乘
            for (int j = num1.length() - 1; j >= 0 || carry != 0; j--) {
                int n1 = j < 0 ? 0 : num1.charAt(j) - '0';
                int sum = n1 * m1 + carry;
                carry = sum / 10;
                temp.append(sum % 10);
            }
            res = addStrings(res,temp.reverse().toString());
        }
        return res;
    }

A solução oficial
Aqui Insert Picture Descrição

public String multiply(String num1, String num2) {
        if (num1.equals("0") || num2.equals("0")) {
            return "0";
        }
        int[] res = new int[num1.length() + num2.length()];
        for (int i = num1.length() - 1; i >= 0; i--) {
            int n1 = num1.charAt(i) - '0';
            for (int j = num2.length() - 1; j >= 0; j--) {
                int n2 = num2.charAt(j) - '0';
                //res[i + j + 1]这个相当于上一次循环的res[i + j],这一次循环相当于进位的值。
                int sum = (res[i + j + 1] + n1 * n2);
                res[i + j + 1] = sum % 10;
                res[i + j] += sum / 10;
            }
        }

        StringBuilder result = new StringBuilder();
        for (int i = 0; i < res.length; i++) {
            if (i == 0 && res[i] == 0) continue;
            result.append(res[i]);
        }
        return result.toString();
    }

作者:breezean
链接:https://leetcode-cn.com/problems/multiply-strings/solution/you-hua-ban-shu-shi-da-bai-994-by-breezean/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
Publicado 98 artigos originais · ganhou elogios 0 · Vistas 2216

Acho que você gosta

Origin blog.csdn.net/weixin_43221993/article/details/103651665
Recomendado
Clasificación