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.
Separate the steps of multiple. It is the same as addition.
for example:
"99" * "99" -> can be stored in a vector as : {8, 17, 10, 1} // the index is the index addition of both strings index.
The only case needs special care is: the result string shouldn’t start with '0'.... and the "0" result case.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string multiply(string num1, string num2) {
if(num1.size() == 0) return num2;
if(num2.size() == 0) return num1;
int m = num1.size();
int n = num2.size();
vector<int> res(m + n, 0);
for(int i = m - 1; i>= 0; --i) {
for(int j = n - 1; j >= 0; --j) {
int tmp = (num1[i] - '0') * (num2[j] - '0');
res[i + j + 1] += tmp % 10;
res[i + j] += tmp / 10;
}
}
for(int i = m + n - 1; i >= 1; --i) {
res[i-1] += res[i] / 10;
res[i] = res[i] % 10;
}
string result = "";
int i = 0;
while(i < m + n && res[i] == 0) {
i++;
}
while(i < n + m) {
result = result + to_string(res[i]);
i++;
}
return result.size() == 0 ? "0" : result; // handle the "0" result case.
}
int main(void) {
string res = multiply("99", "99");
cout << res << endl;
}