Clean JAVA Code with Picture


  • 0
    A

    Multiplication Image

    public String multiply(String num1, String num2) {
        if(num1 == null || num1.isEmpty() || allZero(num1) || num2 == null || num2.isEmpty() || allZero(num2)) return "0";
    	num1 = new StringBuffer(num1).reverse().toString();
    	num2 = new StringBuffer(num2).reverse().toString();
    	int[] sum = new int[num1.length() + num2.length()];
    	
    	for (int i = 0; i < num1.length(); i++)
    		for (int j = 0; j < num2.length(); j++)
    			sum[i + j] += (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
    	StringBuffer buffer = new StringBuffer();
    	int carry = 0;
    	for (int n : sum) {
    		buffer.insert(0, (char) ((n + carry) % 10 + '0'));
    		carry = (n + carry) / 10;
    	}
    	
    	return buffer.charAt(0) == '0' ? buffer.substring(1): buffer.toString();
    }
    
    boolean allZero(String str) {
        for(char ch:str.toCharArray())
            if(ch != '0')
                return false;
        return true;
    }

Log in to reply
 

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