Fast Java Solution


  • 2
    M
    public String multiply(String num1, String num2) {
        StringBuilder s1 = new StringBuilder(num1).reverse();
        StringBuilder s2 = new StringBuilder(num2).reverse();
        
        int l1 = s1.length();
        int l2 = s2.length();
        int[] result = new int[l1 + l2 - 1];
        for(int i = 0; i < l1; i++){
            for(int j = 0; j < l2; j++){
                result[i+j] += (s1.charAt(i) - '0') * (s2.charAt(j) - '0');
            }
        }
        //System.out.println(Arrays.toString(result));
        StringBuilder s = new StringBuilder();
        
        int carry = 0;
        for(int i = 0; i < result.length; i++){
            int currDigit = (result[i] + carry) % 10;
            carry = (result[i]+carry)/10;
            s.insert(0, currDigit);
        }
        
        if(carry!=0){
            s.insert(0, carry);
        }
        
        int i = 0;
        while( i < s.length() && s.charAt(i) == '0'){
            i++;
        }
        if(i ==  s.length() ) s.delete(0,i-1);
        else s.delete(0, i);
        
        return s.toString();
    
            
        
    }

Log in to reply
 

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