Please, improve my Java solution


  • 0
    O
    public class Solution {
        public String multiply(String num1, String num2) {
            char[] first = num1.toCharArray();
        	char[] second = num2.toCharArray();
        	
        	if (first.length == 1 && second.length == 1) {
        		return "" + (Integer.parseInt(num1) * Integer.parseInt(num2)); 
        	}
        	if ((first.length == 1 && first[0] == '0') || (second.length == 1 && second[0] == '0')) {
        		return "0";
        	}
        	
        	int x = 0, y = 0, reminder = 0, prev = 0;
        	
        	int[] res = new int[first.length + second.length];
        	for(int i = 0; i < first.length + second.length; i++) {
        		res[i] = 0;
        	}
        	
        	int i = 0, j = 0;
        	for(i = 0; i < first.length; i++) {
        		reminder = 0;
        		for(j = 0; j < second.length; j++) {
        			x = first[first.length - 1 - i] - '0';
        			y = second[second.length - 1 - j] - '0';
        			x = x * y + reminder + res[i + j];
        			y = x % 10;
        			res[i + j] = y;
        			reminder = (x - y) / 10;
        		}
            	if (reminder != 0) {
            		res[i + j] = reminder;
            	}
        	}
        	
        	StringBuilder str = new StringBuilder();
        	for(int k = i + j - 1; k >= 0; k--) {
        		str.append(res[k]);
        	}
        	if (str.charAt(0) == '0') {
        		str.deleteCharAt(0);
        	}
        	return str.toString();
        }
    }

  • 1
    D
    public String multiply(String num1, String num2) {
        if(num1.length() == 0 || num2.length() == 0) return "";
        int[] res = new int[num1.length() + num2.length()];
        
        for(int i = num1.length()-1; i >= 0; --i){
            for(int j = num2.length()-1; j >= 0; --j){
                // num1[i] and num2[j]
                // remainder is stored at res[i+j+1]
                // carry is stored at res[i+j]
                int first = num1.charAt(i) - '0';
                int second = num2.charAt(j) - '0';
                int product = first * second;
                int sum = product + res[i+j+1];
                res[i+j+1] = sum % 10;
                res[i+j] += sum / 10;
            }
        }
        int i = 0;
        while(i < res.length && res[i] == 0) ++i;
        if(i == res.length) return "0";
        StringBuilder sb = new StringBuilder();
        while(i < res.length) sb.append(res[i++]);
        return sb.toString();
    }

Log in to reply
 

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