24ms Java Solution beats 99%


  • 0
    B

    It's basically how multiplication works. You can draw the processes step by step and you will understand my answer.

    public class Solution {
        public String multiply(String num1, String num2) {
            if (num1 == null || num2 == null) return null;
            if (num1.equals("0") || num2.equals("0")) return "0";
            int length1 = num1.length(), length2 = num2.length();
            if (length1 < length2) return multiply(num2, num1);
            char[] num1Array = num1.toCharArray(), num2Array = num2.toCharArray();
            StringBuilder res = new StringBuilder();
            int carry = 0, sum;
            for (int i = 0; i < length1 + length2; i++) {
                sum = carry;
                for (int j = 0; j < length2; j++) {
                    int index = i-j;
                    if (index>=0 && index < length1)
                        sum += (num1Array[length1 - index - 1] - '0') * (num2Array[length2 - j - 1] - '0');
                }
                res.append(sum % 10);
                carry = sum / 10;
            }
            return res.reverse().charAt(0) == '0'? res.deleteCharAt(0).toString() : res.toString();
        }
    }
    

Log in to reply
 

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