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或long的数值范围的约束。
那我们该如何来计算乘法呢?小时候学过多位数的乘法过程,都是每位相乘然后错位相加,那么这里就是用到这种方法,把错位相加后的结果保存到一个一维数组中,然后分别每位上算进位,最后每个数字都变成一位,然后要做的是去除掉首位0,最后把每位上的数字按顺序保存到结果中即可,代码如下:
class Solution {
public:
string multiply(string num1, string num2)
{
string res;
int n1 = num1.size(), n2 = num2.size();
int k = n1 + n2 - 2, carry = 0;
vector<int> v(n1 + n2, 0);
for (int i = 0; i < n1; ++i)
{
for (int j = 0; j < n2; ++j)
{
v[k - i - j] += (num1[i] - '0') * (num2[j] - '0');
}
}
for (int i = 0; i < n1 + n2; ++i)
{
v[i] += carry;
carry = v[i] / 10;
v[i] %= 10;
}
int i = n1 + n2 - 1;
while (v[i] == 0)
--i;
if (i < 0)
return "0";
while (i >= 0)
res.push_back(v[i--] + '0');
return res;
}
};
本文借鉴于博客这里写链接内容