# 大整数乘法
题目链接:https://kamacoder.com/problempage.php?pid=1237
思路:
我们可以使用模拟手算乘法的方法,即「逐位相乘累加」,对于每一位的乘法结果,我们将其加到相应的结果位置上。最终将累加的结果输出。
具体步骤:
- 初始化结果数组:结果数组的长度应该是两个数字长度之和,因为最大长度的结果不会超过这个长度。
- 逐位相乘:从右往左遍历两个字符串的每一位,逐位相乘,并加到结果数组的相应位置。
- 处理进位:在每一步累加之后处理进位,保证每个位置的值小于10。
将结果数组转化为字符串:从结果数组的最高位开始,忽略前导零,然后将数组转化为字符串。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
string multiply(string num1, string num2) {
int len1 = num1.size();
int len2 = num2.size();
vector<int> result(len1 + len2, 0);
// 逐位相乘
for (int i = len1 - 1; i >= 0; i--) {
for (int j = len2 - 1; j >= 0; j--) {
int mul = (num1[i] - '0') * (num2[j] - '0');
int sum = mul + result[i + j + 1];
result[i + j + 1] = sum % 10;
result[i + j] += sum / 10;
}
}
// 将结果转换为字符串,跳过前导零
string product;
for (int num : result) {
if (!(product.empty() && num == 0)) { // 跳过前导零
product.push_back(num + '0');
}
}
return product.empty() ? "0" : product;
}
int main() {
string num1, num2;
cin >> num1 >> num2;
string result = multiply(num1, num2);
cout << result << endl;
return 0;
}
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
37
38
39
40
41
42
43
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
37
38
39
40
41
42
43
@2021-2025 代码随想录 版权所有 粤ICP备19156078号