Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
思路:纯粹分解乘法 ,按位加
class Solution {
public:
string multiply(string num1, string num2) {
if (num1 == "0" || num2 == "0") return "0";
int m = num1.size();
int n = num2.size();
int *a = new int[m];
int *b = new int[n];
int *c = new int[m + n];
memset(c, 0, (m+n)*sizeof(int));
// print(c, m + n);
for (int i = 0; i < m; i++)
a[i] = num1[i] - '0';
// print(a, m);
for (int i = 0; i < n; i++)
b[i] = num2[i] - '0';
// print(b, n);
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
c[i + j+1] += b[i] * a[j];
}
}
// print(c, m + n);
int next = 0;
int tmp = 0;
for (int i = m + n - 1; i >= 0; i--){
tmp = c[i] + next;
next = tmp / 10;
c[i] = tmp % 10;
}
string res;
int i = 0;
while (c[i] == 0) i++;
for (i; i < m + n ; i++){
res += char(c[i] + '0');
}
return res;
}
};