LeetCode 43. 字符串相乘
原题链接
简单
作者:
autumn_0
,
2025-01-04 21:28:32
,
所有人可见
,
阅读 2
class Solution {
public String multiply(String num1, String num2) {
int n = num1.length(), m = num2.length();
int[] a = new int[n];
int[] b = new int[m];
for(int i = n - 1; i >= 0; i -- ) a[n - 1 - i] = num1.charAt(i) - '0';
for(int i = m - 1; i >= 0; i -- ) b[m - 1 - i] = num2.charAt(i) - '0';
int[] c = new int[n + m];
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;
}
int k = n + m - 1;
while(k > 0 && c[k] == 0) k -- ;
StringBuilder res = new StringBuilder();
while(k >= 0) res.append(c[k -- ]);
return res.toString();
}
}