Multiply Strings

Multiply Strings

题目描述:

给定两个数字字符串,要求计算其数字乘积后的结果。

例子:

具体描述见LeetCode43

解题思路:

首先如果字符串中有一个是0的情况直接返回0;其次,因为我们是从低位算起,所以我们需要逆序原有的字符串;然后需要定义几个变量:(1)进位变量carry(2)表示当前第一个乘数的遍历位置step(3)position表示第一位乘数中取一位和第二个乘数进行计算过程中所在位的位置;在每次从第一个数取一位和第二个乘数进行乘积计算完成时;需要判断是否进位;注意在计算字符乘积的过程中进位需要每次相乘结果上加上。

代码如下:

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
class Solution {
public:
string multiply(string num1, string num2) {
if (num1 == "0" || num2 == "0")
return "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;
}
};