LeetCode 43. 字符串相乘
原题链接
中等
作者:
LangB
,
2020-10-30 13:53:46
,
所有人可见
,
阅读 233
class Solution {
public String multiply(String num1, String num2) {
int n = num1.length(), m = num2.length();
int[] A = new int[n], B = new int[m], C = new int[n + m];
// 将num1每位数字逆序存到A数组
for (int i = 0; i < n; i++) {
A[i] = num1.charAt(n - i - 1) - '0';
}
// 将num2每位数字逆序存到B数组
for (int i = 0; i < m; i++) {
B[i] = num2.charAt(m - i - 1) - '0';
}
// 将每位相乘的结果存到C数组
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
C[i + j] += A[i] * B[j];
}
}
// 处理进位
for (int i = 0, t = 0; i < n + m; i++) {
t += C[i];
C[i] = t % 10;
t /= 10;
}
// 去除前导0
int k = n + m - 1;
while (k > 0 && C[k] == 0) {
k--;
}
StringBuilder res = new StringBuilder();
// 拼接字符串
while (k >= 0) {
res.append((char) (C[k--] + '0'));
}
return res.toString();
}
}