43. Multiply Strings
2017-01-24 15:19
309 查看
Given two non-negative integers
Note:
The length of both
Both
Both
You must not use any built-in BigInteger library or
convert the inputs to integer directly.
求两个字符串表示的数相乘的结果,以字符串形式表示。和多项式的相乘类似,结果res的第n位是所有符合i+j=n的第i和j项相乘得到的,因为是十进制,所以取mod 10的结果,多出的部分进位。代码如下:
class Solution
{
public:
string multiply(string num1, string num2)
{
int m = num1.size(), n = num2.size();
if(m == 0 || n == 0) return 0;
string res(m + n, '0');
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
for(int i = 0; i < m; ++i)
{
int r = 0;
for(int j = 0; j < n; ++j)
{
int tmp = (res[i + j] - '0') + (num1[i] - '0') * (num2[j] - '0') + r;
res[i + j] = tmp % 10 + '0';
r = tmp / 10;
}
res[i + n] += r;
}
reverse(res.begin(), res.end());
size_t pos = res.find_first_not_of("0");
if(pos != string::npos)
{
return res.substr(pos);
}
return "0";
}
};
num1and
num2represented as strings, return the product of
num1and
num2.
Note:
The length of both
num1and
num2is < 110.
Both
num1and
num2contains only digits
0-9.
Both
num1and
num2does not contain any leading zero.
You must not use any built-in BigInteger library or
convert the inputs to integer directly.
求两个字符串表示的数相乘的结果,以字符串形式表示。和多项式的相乘类似,结果res的第n位是所有符合i+j=n的第i和j项相乘得到的,因为是十进制,所以取mod 10的结果,多出的部分进位。代码如下:
class Solution
{
public:
string multiply(string num1, string num2)
{
int m = num1.size(), n = num2.size();
if(m == 0 || n == 0) return 0;
string res(m + n, '0');
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
for(int i = 0; i < m; ++i)
{
int r = 0;
for(int j = 0; j < n; ++j)
{
int tmp = (res[i + j] - '0') + (num1[i] - '0') * (num2[j] - '0') + r;
res[i + j] = tmp % 10 + '0';
r = tmp / 10;
}
res[i + n] += r;
}
reverse(res.begin(), res.end());
size_t pos = res.find_first_not_of("0");
if(pos != string::npos)
{
return res.substr(pos);
}
return "0";
}
};
相关文章推荐
- [Leetcode] #43 Multiply Strings
- LeetCode 43. Multiply Strings
- [LeetCode]43 Multiply Strings
- Leetcode43 Multiply Strings
- Leetcode 43. Multiply StringsI
- Leetcode 43. Multiply Strings
- 43. Multiply Strings
- 43. Multiply Strings
- 43. Multiply Strings
- LeetCode43 Multiply Strings
- Leetcode:43. Multiply Strings
- [LeetCode] 415 Add Strings && 67 Add Binary && 43 Multiply Strings
- 数学:43 : Multiply Strings
- [leetcode 43] Multiply Strings
- LeetCode 43 - Multiply Strings
- LeetCode 43 Multiply Strings
- [LeetCode 43] Multiply Strings
- 43. Multiply Strings
- Leetcode 43 Multiply Strings