Share My Solution based on Add String


  • 0
    A
        public class Solution {
        
        public String multiply(String num1, String num2) {
            String result = "0";
            for (int i=num2.length()-1; i>=0; i--) {
                String current = "0";
                int digit = num2.charAt(i) - '0';
                for (int j=0; j<digit; j++) {
                    current = add(current, num1);
                }
                if (current.equals("0")) continue;
                StringBuffer strBuf = new StringBuffer(current);
                for (int j=0; j<num2.length()-1-i; j++) {
                    strBuf.append('0');
                }
                
                result = add(result, strBuf.toString());
            }
            return result;
       }
       
       public String add(String num1, String num2) {
           int maxLen = Math.max(num1.length(), num2.length());
           char[] digits = new char[maxLen];
           int carry = 0;
           for (int i=0; i<maxLen; i++) {
               int digit1 = i >= num1.length() ? 0 : (num1.charAt(num1.length() - 1 - i) - '0');
               int digit2 = i >= num2.length() ? 0 : (num2.charAt(num2.length() - 1 - i) - '0');
               int value = carry + digit1 + digit2;
               digits[maxLen - 1 - i] = (char)((value % 10) + '0');
               carry = value/10;
           }
           StringBuffer strBuf = new StringBuffer();
           if (carry > 0) {
               strBuf.append(carry);
           }
           for (int i=0; i<maxLen; i++) {
               strBuf.append(digits[i]);
           }
           return strBuf.toString();
       }
    }

Log in to reply
 

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