leetcode.43 字符串相乘(大数乘法)

给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。

示例 1:

输入: num1 = "2", num2 = "3"
输出: "6"

示例 2:

输入: num1 = "123", num2 = "456"
输出: "56088"

思路:模拟大数加法,然后模拟乘法,得的每一步的子结果,用大数加法将结果统计,即大数乘法的结果。

   public String multiply(String num1, String num2) {
        if (num1.length() < num2.length()) {
            String temp = num1;
            num1 = num2;
            num2 = temp;
        }
        num1 = "0" + num1;
        num2 = "0" + num2;
       /* for (int i = 1; i <= num1.length() - num2.length(); i--) {
            num2 = "0" + num2;
        }*/
        List list = new ArrayList<>();
        int jw = 0;
        int k = 0;
        for (int i = num2.length() - 1; i >= 0; i--) {
            String s = "";
            for (int j = num1.length() - 1; j >= 0; j--) {

                int num1_temp = Integer.parseInt(String.valueOf(num1.charAt(j)));
                int num2_temp = Integer.parseInt(String.valueOf(num2.charAt(i)));
                int res = num1_temp * num2_temp + jw;
                s = String.valueOf(res % 10) + s;
                if (res >= 10) {
                    jw = res / 10 % 10;
                } else {
                    jw = 0;
                }
            }
            list.add(s + zero(k));
            k++;
        }

        String s = "0";
        for (String s_res : list) {
            s = add(s, s_res);
            //System.out.println(s_res);
        }

        String pz = zero(s.length());
        if (pz.equals(s))
            return "0";

        //去0
        s = "0" + s;

        int index = 0;

        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) != '0') {
                index = i;
                break;
            }
        }
        return s.substring(index, s.length());
    }


    public String add(String s1, String s2) {

        if (s1.length() < s2.length()) {
            String s3 = s1;
            s1 = s2;
            s2 = s3;
        }
        int l1 = s1.length();
        int l2 = s2.length();
        for (int i = 1; i <= l1 - l2; i++) {
            s2 = "0" + s2;
        }

        String s = "";
        int jw = 0;
        for (int i = s1.length() - 1; i >= 0; i--) {
            int s1_num = Integer.parseInt(String.valueOf(s1.charAt(i)));
            int s2_num = Integer.parseInt(String.valueOf(s2.charAt(i)));
            int res = jw + s1_num + s2_num;
            if (res >= 10) {
                jw = 1;
                s = String.valueOf(res - 10) + s;
            } else {
                jw = 0;
                s = String.valueOf(res) + s;
            }
        }
        return s;
    }

    public String zero(int n) {
        String s = "";
        for (int i = 1; i <= n; i++) {
            s = "0" + s;
        }
        return s;
    }

你可能感兴趣的:(leetcode.43 字符串相乘(大数乘法))