給定兩個以字串形式表示的非負整數 num1 和 num2,返回 num1 和 num2 的乘積,它們的乘積也表示爲字串形式。
輸入: num1 = "2", num2 = "3"
輸出: "6"
輸入: num1 = "123", num2 = "456"
輸出: "56088"
/*
* @Author: motongxue
* @Date: 2020-08-13 19:53:33
* @LastEditors: motongxue
* @LastEditTime: 2020-08-13 20:16:56
* @Blog: https://motongxue.cn
* @Description: file content
*/
public class multiply43 {
public String multiply(String num1, String num2) {
if (num1.equals("0") || num2.equals("0"))
return "0";
int len1 = num1.length();
int len2 = num2.length();
int[] n1 = new int[len1 + 1];
int[] n2 = new int[len2 + 1];
int[] ans = new int[len1 + len2 + 10];
for (int i = 0; i < len1; i++)
n1[len1 - i] = num1.charAt(i) - '0';
for (int i = 0; i < len2; i++)
n2[len2 - i] = num2.charAt(i) - '0';
for(int i=1;i<=len1;i++){ //相當於學習小學的乘法,一位數一位數相乘,然後相加起來
for(int j=1;j<=len2;j++){
ans[i+j-1] += n1[i]*n2[j];
ans[i+j] += ans[i+j-1]/10;
ans[i+j-1] %= 10;
}
}
int sum = ans[len1+len2]==0?len1+len2-1:len1+len2;
StringBuffer res = new StringBuffer();
for(int i=sum;i>0;i--)
res.append(ans[i]);
return res.toString();
}
}