您的位置:首页 > 其它

leetcode 43. Multiply Strings

2017-10-10 22:56 435 查看
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

The length of both num1 and num2 is < 110.

Both num1 and num2 contains only digits 0-9.

Both num1 and num2 does not contain any leading zero.

You must not use any built-in BigInteger library or convert the inputs to integer directly.

题目大意:

求两个大数的乘积

思路:

模拟乘法,O(n^2)的解法...

class Solution {
public:
string multiply(string num1, string num2) {
int n = num1.size();
int m = num2.size();
vector<int>v(500);
int k = 0;
for (int i = n - 1; i >= 0; --i) {
k = n - i - 1;
for (int j = m - 1; j >= 0; --j) {
v[k] += (num1[i] - '0') * (num2[j] - '0');
if (v[k] >= 10) {
v[k+1] += v[k]/10;
v[k] %= 10;
}
++k;
}
}
string ans = "";
int mark = 0;
for (int i = 500 - 1; i >= 0; --i) {
if (v[i] == 0 && mark == 0) continue;
else {
mark = 1;
ans += v[i] + '0';
}
}
if (ans == "") ans += '0';
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: