43. Implementation of the shortest code of multiply strings | Java

43.multiply Strings

[thinking]
The exact multiplication of large Numbers tests the bitwise operation of strings. The result is cached in an int array. The advantage of using an int array is that the value of each int can be greater than 10:

    public String multiply(String num1, String num2) {
        int len1 = num1.length(), len2 = num2.length(), len = len1 + len2, count = 0;
        int[] arr = new int[len];
        for (int i = len1 - 1; i >= 0; i--) {
            int bit1 = num1.charAt(i) - '0';
            for (int j = len2 - 1, k = j + i + 1; j >= 0; j--, k--) {
                int temp = bit1 * (num2.charAt(j) - '0') + arr[k];
                arr[k] = temp % 10;
                arr[k - 1] += temp/10;
            }
        }
        String s = "";
        for (int i = 0; i < arr.length; i++)
            s += arr[i];
        while(count < len && s.charAt(count++) == '0');
        return s.substring(count - 1);
    }

311/311
13 Ms Your Runtime beats 29.13 per cent of javasubmissions.

Of course, I laughed when I saw something simple and funny on the Internet:

    public String multiply(String num1, String num2) {
        return new BigInteger(num1).multiply(new BigInteger(num2)) + "";
    }

Of course, this method doesn’t work. It’s designed to make people laugh.

Welcome to optimize!

Read More: