给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
示例 1:
输入: num1 = "2", num2 = "3"
输出: "6"
示例 2:
输入: num1 = "123", num2 = "456"
输出: "56088"
说明:
num1 和 num2 的长度小于110。
num1 和 num2 只包含数字 0-9。
num1 和 num2 均不以零开头,除非是数字 0 本身。
不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。
public String multiply(String num1, String num2) {
int n1 = num1.length(), n2 = num2.length();
int[] res = new int[n1 + n2];
for(int i = n1-1; i >= 0; i --) {
for(int j = n2-1; j >= 0; j--) {
int temp = res[i+j+1] + (num1.charAt(i)-'0') * (num2.charAt(j)-'0');
res[i+j] += temp/10;
res[i+j+1] = temp%10;
}
}
int index = 0;
while(index < res.length && res[index] == 0)
index ++;
StringBuilder sb = new StringBuilder();
while(index < res.length) {
sb.append(res[index]);
index ++;
}
if(sb.length() == 0)
return "0";
return sb.toString();
}