Java solution for multiply


  • 3
    D
    public String multiply(String num1, String num2) {
    	int length1 = num1.length();
    	int length2 = num2.length();
    	int[] result = new int[length1 + length2];
    	for (int i = length1 - 1; i >= 0; i--) {
    		int tem1 = num1.charAt(i) - '0';
    		for (int j = length2 - 1; j >= 0; j--) {
    			int tem2 = num2.charAt(j) - '0';
    			int temMultiply = tem1 * tem2;
    			int carry = temMultiply / 10;
    			int temResult = temMultiply % 10;
    			result[i + j + 1] += temResult;
    			if (result[i + j + 1] >= 10) {
    				result[i + j + 1] = result[i + j + 1] % 10;
    				carry++;
    			}
    			result[i + j] += carry;
    			if (result[i + j] >= 10) {
    				result[i + j] = result[i + j] % 10;
    				result[i + j - 1] += 1;
    			}
    		}
    
    	}
    	StringBuffer sb = new StringBuffer();
    	boolean start = false;
    	for (int k = 0; k <= length1 + length2 - 1; k++) {
    		if (result[k] != 0) {
    			start = true;
    		}
    		if (start) {
    			sb.append(result[k]);
    		}
    	}
    	if (!start)
    		return 0 + "";
    	return sb.toString();
    }

Log in to reply
 

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