My JAVA solution


  • 0
    Q
    public class Solution {
       public String multiply(String num1, String num2) {
            if (num1.equals("0") || num2.equals("0")){
                return "0";
            }
            List<StringBuilder> brokenUP = new ArrayList<StringBuilder>();
            int count = 0;
            for (int i=num1.length()-1;i>=0;i--){
                char ch = num1.charAt(i);
                StringBuilder result = new StringBuilder(String.valueOf(ch));
                for (int j=0;j<count;j++){
                	result.append('0');
                }
                brokenUP.add(result);
                count++;
            }
            
            List<StringBuilder> multiplicationResults = new ArrayList<StringBuilder>();
            for (StringBuilder s: brokenUP){
            	int carry = 0;
            	int number = s.charAt(0)-'0';
            	StringBuilder result = new StringBuilder();
            	for (int j=num2.length()-1;j>=0;j--){
            		int ch =  num2.charAt(j)-'0';
            		int val = number*ch + carry;
            		carry = val/10;
            		result.append(val%10);
            	}
            	if (carry>0){
            		result.append(carry);
            	}
            	for (int j=0;j<s.length()-1;j++){
            		result.insert(0, '0');
            	}
            	multiplicationResults.add(result);
            }
            StringBuilder sum = multiplicationResults.remove(multiplicationResults.size()-1);
                   
            for (StringBuilder toAdd : multiplicationResults){
            	int carry = 0;
            	StringBuilder newSum = new StringBuilder();
            	for (int j=0;j<toAdd.length();j++){
            		int c1 = toAdd.charAt(j)-'0';
            		int c2 = sum.charAt(j)-'0';
            		int val = c1+c2+carry;
            		carry = val/10;
            		newSum.append(val%10);
            	}
            	for (int k = toAdd.length();k<sum.length();k++){
            		int c2 = sum.charAt(k)-'0';
            		int val = c2+carry;
            		carry = val/10;
            		newSum.append(val%10);
            	}
            	if (carry>0){
            		newSum.append(carry);
            	}
            	sum = newSum;
            }
            return sum.reverse().toString();
        }
    }

Log in to reply
 

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