Just post my Java code [inspired by most-voted posts]


  • 1
    M

    learned a lot from others...

    /*
        if we set num1.length()+num2.length() as the length of result string, then
        num1[i] * num2[j] contributes to result[i+j] and result[i+j+1].
    */
    public class Solution {
        public String multiply(String num1, String num2) {
            if (num1.equals("0") || num2.equals("0")) {
                return "0";
            }
            int[] result = new int[num1.length() + num2.length()];
            for (int i = num1.length() - 1; i >= 0; --i) {
                for (int j = num2.length() - 1; j >= 0; --j) {
                    int contribution = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
                    int sum = result[i + j + 1] + contribution;
                    result[i + j + 1] = sum % 10;
                    result[i + j] += sum / 10;
                }
            }
            StringBuilder ans = new StringBuilder();
            for (int i = result[0] == 0 ? 1 : 0; i < result.length; ++i) {
                ans.append(result[i]);
            }
            return ans.toString();
        }
    }

Log in to reply
 

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