43. Multiply Strings

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.
  • 直接乘會溢出,所以每次都要兩個single digit相乘,最大81,不會溢出。
  • 比如385 * 97, 就是個位=5 * 7,十位=8 * 7 + 5 * 9 ,百位=3 * 7 + 8 * 9 …
    可以每一位用一個Int表示,存在一個int[]裏面。
  • 這個數組最大長度是num1.len + num2.len,比如99 * 99,最大不會超過10000,所以4位就夠了。
  • 這種個位在後面的,不好做(10的0次方,可惜對應位的數組index不是0而是n-1),
    所以乾脆先把string reverse了代碼就清晰好多。
  • 最後結果前面的0要清掉。

public class Solution {
    public String multiply(String num1, String num2) {
        num1 = new StringBuilder(num1).reverse().toString();
    	num2 = new StringBuilder(num2).reverse().toString();
    	
    	int[] d = new int[num1.length() + num2.length()];
    	for(int i=0; i<num1.length(); i++){
    		int a = num1.charAt(i) - '0';
    		for(int j=0; j<num2.length(); j++){
    			int b = num2.charAt(j) - '0';
    			d[i+j] += a*b;
    		}    		
    	}
    	
    	StringBuffer sb = new StringBuffer();
    	for(int i=0; i<d.length; i++){
    		int digit = d[i]%10;
    		int carry = d[i]/10;
    		sb.insert(0, digit);
    		if(carry > 0){
    			d[i+1] += carry;
    		}
    	}
    	
    	while(sb.length() > 0 && sb.charAt(0) == '0'){
    		sb.deleteCharAt(0);
    	}
    	
    	return sb.length() == 0 ? "0" : sb.toString();
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章