题目
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.
思路
最后要对结果进行校正,因为有可能 result[i]>10 .
while(i<result.size()) {
result[i+1] += result[i]/10;
result[i] = result[i]%10;
i++;
}
完整代码:
class Solution {
public:
string multiply(string num1, string num2) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int len1 = num1.length();
int len2 = num2.length();
if(len1==0 || len2==0)
return "0";
vector<int> result(len1+len2+2,0);
reverse(num1.begin(),num1.end());
reverse(num2.begin(),num2.end());
for(int i=0;i<len1;i++){
for(int j=0;j<len2;j++) {
int a = num1[i]-'0';
int b = num2[j]-'0';
int product = a*b;
result[i+j] += product%10;
result[i+j+1] += product/10;
}
}
int i=0;
while(i<result.size()) {
result[i+1] += result[i]/10;
result[i] = result[i]%10;
i++;
}
string res = "";
int k = len1+len2+1;
while(result[k]==0) k--;
if(k==-1) return "0";
while(k>=0) {
res = res+char(result[k]+'0');
k--;
}
return res;
}
};
也有其他代码:
从后往前计算
string multiply(string num1, string num2) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!num1.compare("0") || !num2.compare("0")) return "0";
int len1 = num1.length();
int len2 = num2.length();
string result(len1+len2, '0');
int tmp, carry;
int i, j;
for (j = len2-1; j >= 0; j--) {
carry = 0;
for (i = len1-1; i >= 0; i--) {
tmp = (num1[i]-'0') * (num2[j]-'0') + carry + (result[i+j+1]-'0');
carry = tmp / 10;
result[i+j+1] = (tmp % 10) + '0';
}
result[j] = carry + '0';
}
if (result[0] == '0') {
return string(result.begin()+1, result.end());
}
else {
return result;
}
}