【LeetCode】43. Multiply Strings

Multiply Strings

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.

将乘积逐位逆序存放在int数组result中。

记num1当前为第i位,num2当前为第j位,则乘积存放在result[(n1-1-i)+(n2-1-j)]中。

注意进位,当num1[i]与num2的每一位都相乘之后,如果仍有进位,需要存放在result[(n1-1-i)+n2]中。

最后将result逆序,去掉前面的0.但是如果全为0就返回"0"。

class Solution {
public:
string multiply(string num1, string num2) {
int n1 = num1.size();
int n2 = num2.size();
vector<int> result(n1+n2);
string resultStr; for(int i = n1-; i >= ; i --)
{// for num1[i]
int carry = ;
int val1 = num1[i] - '';
for(int j = n2-; j >= ; j --)
{// for num2[j]
int val2 = num2[j] - '';
int res = val1 * val2;
int ind = (n1--i)+(n2--j);
result[ind] += carry;
result[ind] += res; carry = result[ind] / ;
result[ind] %= ;
}
if(carry != )
{
int ind = (n1--i)+n2;
result[ind] += carry;
}
}
//reverse result
reverse(result.begin(), result.end());
int i;
for(i = ; i < n1+n2; i ++)
{
if(result[i] != )
break;
}
if(i == n1+n2)
//all 0
return "";
else
{
for(; i < n1+n2; i ++)
{
resultStr += (result[i] + '');
}
return resultStr;
}
}
};

【LeetCode】43. Multiply Strings

上一篇:LeetCode解题报告—— Combination Sum & Combination Sum II & Multiply Strings


下一篇:linux command ------ ls