Multiply Strings

Multiply Strings

题目描述:

给定两个代表数字的字符串,要求计算其乘积的结果,返回其字符串形式。

例子:

具体描述见LeetCode43

解题思路:

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public:
string multiply(string num1, string num2) {
if (num1 == "0" || num2 == "0")
return "0";
//如果乘数中有任意一个是0的情况下直接返回0即可
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
//逆序字符串从低位开始处理
int carry =0;
int step = 0;
string res = "";
for (int i = 0; i < num1.size(); i++){
int position = step;
for (int j = 0; j < num2.size(); j++){
int num = (num1[i] - '0') * (num2[j] - '0') + carry;
if (position < res.size()){
num += res[position] - '0';
res[position] = num % 10 + '0';
}else{
res.append(1, (num % 10) + '0');
}
carry = num / 10;
position++;
}
if (carry > 0){
res.append(1, carry + '0');
}
step++;
carry = 0;
}
reverse(res.begin(), res.end());
return res;
}
};