Java solution, very slow


  • 0
    R
     public String multiply(String num1, String num2) {
        if(num1.equals("0")||num2.equals("0")){
            return "0";
        }
        Set<StringBuilder> set = new HashSet<>();
        for(int index=num2.length()-1; index>=0;index--){
            StringBuilder res = multipyStringWithSingleChar(num1,num2.charAt(index));
            for(int add=num2.length()-1; add>index;add--){
                res.append("0");
            }
            set.add(res);
        }
        StringBuilder res = null;
        for(StringBuilder s : set){
            res = addTwoString(res,s);
        }
        return res.toString();
    }
    private StringBuilder multipyStringWithSingleChar(String num1, Character ch){
        StringBuilder result = new StringBuilder();
        int added=0;
        int multify = ch-'0';
        if(multify==0 || num1==null || num1.length()==0){
            return new StringBuilder("0");
        }
        for(int index=num1.length()-1; index>=0; index--){
            Character c = num1.charAt(index);
            int num = c-'0';
            StringBuilder s = new StringBuilder(String.valueOf((added + multify*num)%10));
            result = s.append(result);
            added = (added + multify*num)/10;
        }
        if(added!=0){
            StringBuilder s = new StringBuilder(String.valueOf(added));
            result = s.append(result);
        }
        return result;
    
    }
    
    private StringBuilder addTwoString(StringBuilder str1, StringBuilder str2){
        int added=0;
        if(str1==null&&str2==null){
            return new StringBuilder("0");
        }
        if(str1==null){
            return str2;
        }
        if(str2==null){
            return str1;
        }
        if(str1.length()>str2.length()){
            return addTwoString(str2, str1);
        }
    
        StringBuilder result = new StringBuilder();
    
        int diff = str2.length()-str1.length();
    
    
        for(int index=0; index<diff;index++){
            StringBuilder zero = new StringBuilder("0");
            str1 = zero.append(str1);
        }
    
        for(int index=str1.length()-1;index>=0;index--){
            int temp = str1.charAt(index)-'0'+str2.charAt(index)-'0'+added;
            StringBuilder bitResult = new StringBuilder(String.valueOf(temp%10));
            result = bitResult.append(result);
            added = temp/10;
        }
    
        
        if(added!=0){
            StringBuilder s = new StringBuilder(String.valueOf(added));
            result = s.append(result);
        }
        return result;
    }

Log in to reply
 

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