My simple solution


  • 0
    P
        public String multiply(String num1, String num2) {
            if (num1 == null || num1.isEmpty()) {
                return num2;
            }
            
            if (num2 == null || num2.isEmpty()) {
                return num1;
            }
            
            if (num1.equals("0") || num2.equals("0")) {
                return "0";
            }
            
            int m = num1.length();
            int n = num2.length();
            
            StringBuffer sb = new StringBuffer();
            
            int carry = 0;
            for (int idx = m+n-2 ; idx >= 0 ; idx--) {
                int sum = 0;
                
                int i = idx > m - 1 ? m-1 : idx;
    			int j = idx - i;
                for (; i >= 0 && i < m && j >= 0 && j < n ; i--, j++) {
                    sum += (num1.charAt(i) - '0')*(num2.charAt(j) - '0');
                }
                
                sum += carry;
                sb.insert(0, sum % 10);
                carry = sum / 10;
            }
            if (carry > 0) {
            	sb.insert(0,  carry);
            }
            
            return sb.toString();
        }
    }```

Log in to reply
 

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