Java Solution to Multiply Strings


  • 0
    T
    class Solution {
    
        public String multiply(String num1, String num2) {
            int[] res = new int[num1.length()+num2.length()];
            
            for(int i=num2.length()-1;i>=0;i--){
                for(int j =num1.length()-1;j>=0;j--){
                    res[i+j+1] += (num1.charAt(j)-'0')*(num2.charAt(i)-'0');
                    res[i+j] += res[i+j+1] / 10;
                    res[i+j+1] = res[i+j+1] %10;             
                }            
            }
            
            StringBuilder sb = new StringBuilder();
            if(res.length==0) sb.append("0");
            else{
                int m =0;
                
                while(m!=res.length&&res[m]==0){
                    m++;
                }
                for(; m<res.length;m++){
                    sb.append(res[m]);
                }
            }
            String out = sb.toString();
            if(out.equals("")) return "0";
            return out;
        }
    }
    

Log in to reply
 

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