给定两个以字符串形式表示的非负整数 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 static String multiply(String num1, String num2) {
if ("0".equals(num1) || "0".equals(num2)) {
return "0";
}
//让num1乘以num2的每一位
if (num1.length() < num2.length()) {
return multiply(num2, num1);
}
int[] res = new int[num1.length() + num2.length()];
for (int i = num2.length() - 1; i >= 0; i--) {
for (int j = num1.length() - 1; j >= 0; j--) {
//i+j+1位置可能之前已经有值,所以乘当前之后还要加上原来的
int temp = (num1.charAt(j) - '0') * (num2.charAt(i) - '0') + res[i + j + 1];
res[i + j + 1] = temp % 10;
//然后将进位给到前一位
res[i + j] += temp / 10;
}
}
StringBuilder result = new StringBuilder();
//数组首位可能是0,比如123*456=056088
if(res[0]!=0){
result.append(res[0]);
}
for (int i = 1; i < res.length; i++) {
result.append(res[i]);
}
return result.toString();
}