重载乘法
描述
给定两个个字符串 num1 和 num2, 求 num1 * num2
样例
样例11
2输入: num1 = "2" num2 = "3"
输出: "6"
样例21
2输入: num1 = "123", num2 = "456"
输出: "56088"
思路
写三个函数
- 计算两个字符串的乘积
- 计算两个字符串的和
- 计算一个字符串和一个单一的数字的结果
第一个函数调用第二个和第三个函数
也可以这样,result[i+j]
1
2
3int temp = (result[i + j] - '0') + carry + ((num1[i] - '0')*(num2[j] - '0'));
result[i + j] = (temp % 10) + '0';
carry = (temp / 10);
代码
1 | class Solution { |
另一种方法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
37class Solution {
public:
string multiply(string num1, string num2) {
string result(num1.size() + num2.size(),'0');
// cout << result <<endl;
reverse(begin(num1),end(num1));
reverse(begin(num2),end(num2));
int carry = 0;
for(int i = 0; i < num1.size(); ++i){
for(int j = 0; j < num2.size(); ++j){
int temp = (result[i + j] - '0') + carry + ((num1[i] - '0')*(num2[j] - '0'));
result[i + j] = (temp % 10) + '0';
carry = (temp / 10);
}
if(carry){
int temp = (result[i + num2.size()] - '0') + carry;
result[i+ num2.size()] = (temp%10) + '0';
carry = temp/10;
}
}
if(carry){
result[num1.size() + num2.size() - 1] += ((result[num1.size() + num2.size() - 1] - '0') + carry) + '0';
}
reverse(begin(result),end(result));
int zi = 0;
for(;zi != result.size() && result[zi] == '0'; zi++);
if(zi == result.size()){
return "0";
}
return result.substr(zi);
}
};