JAVA code, beat 96.90%


  • 2
    F
    public String multiply(String num1, String num2) {
        char[] s1 = num1.toCharArray();
        char[] s2 = num2.toCharArray();
        int len1 = s1.length;
        int len2 = s2.length;
        int[] ans = new int[len1 + len2];
        for (int i = len2 - 1; i >= 0; i--) {
            for (int j = len1 - 1; j >= 0; j--) {
                ans[len1 + len2 - i - j - 2] += (s2[i] - '0') * (s1[j] - '0');
            }
        }
        for (int i = 0; i < len1 + len2 - 1; i++) {
            ans[i + 1] += ans[i] / 10;
            ans[i] %= 10;
        }
        StringBuilder stringBuilder = new StringBuilder();
        int i = len1 + len2 - 1;
        while (i >= 0 && ans[i] == 0)
            i--;
        if (i < 0)
            return "0";
        while (i >= 0) {
            stringBuilder.append(ans[i]);
            i--;
        }
        return stringBuilder.toString();
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.