Given two non-negative integers num1
and num2
represented
as strings, return the product of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - 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();
}
}