Ac solution code


  • 0

    The basic idea is to multiply digit with digit, level by level. A little trick is how to deal with the carry, as the following:

    public String multiply(String num1, String num2) { 
        int len1 = num1.length(), len2 = num2.length();
        int digits[] = new int[len1 + len2];
    
        for (int i = len1 - 1; i >= 0; i--) { 
            for (int j = len2 - 1; j >= 0; j--) {
                int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
                int sum = mul + digits[i + j + 1];
                
                digits[i + j + 1] =  sum % 10;
                digits[i + j]    +=  sum / 10;// Add the carry to the next digit in advance
            }
        }
    
        StringBuilder sb = new StringBuilder();
        for (int i : digits) if (!(sb.length()==0 && i == 0)) sb.append(i);    
        return sb.length() == 0 ? "0" : sb.toString();
    }

Log in to reply
 

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