官方题解, 我自己写了一点注释
class Solution {
public String multiply(String num1, String num2) {
// 若两个数其中一个为0, 则直接输出为0
if (num1.equals("0") || num2.equals("0")) {
return "0";
}
// 设置一个字符串记录结果
String ans = "0";
// 记录两个数的长度
int m = num1.length(), n = num2.length();
for (int i = n - 1; i >= 0; i--) {
// 创建一个sb来记录当前的结果
StringBuffer curr = new StringBuffer();
int add = 0;
// 一位数一位数的算, 高位的需要先添加0, 然后直接算
for (int j = n - 1; j > i; j--) {
curr.append(0);
}
// 从字符串中拿出要算的数字 ([-'0'] 这个操作是为了把字符转换为数字)
int y = num2.charAt(i) - '0';
for (int j = m - 1; j >= 0; j--) {
// 从字符串中取出要算的数字
int x = num1.charAt(j) - '0';
// 计算两个数字的乘积, 再加上add
int product = x * y + add;
// 把余数加入到curr中记录
curr.append(product % 10);
// 把余数以外的用add记录, 下一次运算继续使用
add = product / 10;
}
// 当计算完一位数的时候, 若add不为0, 则记录下他的最后一位数
if (add != 0) {
curr.append(add % 10);
}
ans = addStrings(ans, curr.reverse().toString());
}
return ans;
}
// 字符串相加
public String addStrings(String num1, String num2) {
// 记录两个字符串的长度
int i = num1.length() - 1, j = num2.length() - 1, add = 0;
// 创建一个sb来记录结果
StringBuffer ans = new StringBuffer();
while (i >= 0 || j >= 0 || add != 0) {
int x = i >= 0 ? num1.charAt(i) - '0' : 0;
int y = j >= 0 ? num2.charAt(j) - '0' : 0;
int result = x + y + add;
ans.append(result % 10);
add = result / 10;
i--;
j--;
}
// 因为sb的append是在字符串结尾加入, 所以结果需要反转字符串
ans.reverse();
return ans.toString();
}
}