Beats 96% 25ms Fast and easy solution


  • 0
    S
    public String multiply(String num1, String num2) {
            if (num1.length() == 1 && num1.charAt(0) == '0' || num2.length() == 1 && num2.charAt(0) == '0') return "0";
    	int n = num1.length() + num2.length();
    	int[] res = new int[n];
    	char[] c1 = num1.toCharArray(), c2 = num2.toCharArray();
    	for (int i = c2.length-1; i >= 0; i--) {
    		int carry = 0;
    		int len = n-- - 1;
    		for (int j = c1.length-1; j >= 0 ; j--) {
    			int mult = (c1[j]-'0')*(c2[i]-'0') + res[len] + carry;
    			res[len--] = mult%10;
    			carry = mult/10;
    		}
    		res[len] = carry;
    	}
    
    	StringBuilder sb = new StringBuilder();
    	for (int i = res[0]!=0? 0:1; i < res.length; i++) 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.