题意:大数乘法。
思路:简单模拟。
class Solution {
public:
string multiply(string num1, string num2) {
vector<string> re;
std::reverse(num1.begin(), num1.end());
std::reverse(num2.begin(), num2.end());
for(int i = 0; i < num1.length(); i ++) {
string tempre;
for(int j = 0; j < i; j++) tempre += '0';
int c = 0;
for(int j = 0; j < num2.length(); ++ j) {
int a = num1[i] - '0';
int b = num2[j] - '0';
tempre += (a * b + c) % 10 + '0';
c = (a * b + c) / 10;
}
if(c) tempre += c + '0';
std::reverse(tempre.begin(), tempre.end());
re.push_back(tempre);
}
string rre = re[0];
for(int i = 1; i < re.size(); ++ i) {
rre = addStrings(rre, re[i]);
}
int z = 0;
for(z = 0; z < rre.length(); ++ z) {
if(rre[z] != '0') break;
}
if(z == rre.length()) rre = '0';
return rre;
}
string addStrings(string num1, string num2) {
string re;
int c = 0;
std::reverse(num1.begin(), num1.end());
std::reverse(num2.begin(), num2.end());
int i = 0;
while(i < num1.length() ||i < num2.length()) {
int a = 0;
int b = 0;
if(i < num1.length()) a = num1[i] - '0';
if(i < num2.length()) b = num2[i] - '0';
re += (a + b + c) % 10 + '0';
c = (a + b + c) / 10;
i ++;
}
if(c) re += c + '0';
std::reverse(re.begin(), re.end());
return re;
}
};