您的位置:首页 > 其它

【Leetcode】【Medium】Multiply Strings

2015-03-10 02:04 253 查看
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.

解题:

模拟乘法运算,可以完全按照模拟的思路,用num1的每一位乘num2,得到的数组按位保存在结果字符串中,并不断更新。

先把字符串反转,在逻辑上思路会更加清晰,当然不反转也可以。

class Solution {
public:
string multiply(string num1, string num2) {
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
int l1 = num1.size();
int l2 = num2.size();
string res(l1 + l2, '0');
int carry, d;

for (int i = 0; i < l1; ++i) {
int n1 = num1[i] - '0';
carry = 0;
for (int j = 0; j < l2; ++j) {
int n2 = num2[j] - '0';
d = n1 * n2 + carry + (res[i+j] - '0');
carry = d / 10;
res[i+j] = '0' + (d - carry * 10);
}

int idx = 0;
while (carry != 0) {
d = (res[i+l2+idx] - '0') + carry;
carry = d / 10;
res[i+l2] = '0' + (d - carry * 10);
idx++;
}
}

while (!res.empty() && res.back() == '0')
res.pop_back();
if (res.empty())
return "0";
reverse(res.begin(), res.end());
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: