您的位置:首页 > 其它

[leetcode] 43. Multiply Strings 解题报告

2016-02-21 15:03 555 查看
题目链接:https://leetcode.com/problems/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.

思路:用数组来模拟相乘,其结果的长度最多为(len1 + len2),最小为(len1 + len2 -1).并且两个位置i,j的字符相乘的结果的位置是(i+j),应还要考虑进位.

最后还要注意乘积为0的情况,应该将字符串变为只有一个0.

代码如下:

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