Contents

  • 按虚线的方向将相乘的结果相加(虚线上的横纵坐标和为i+J)
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
44
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>

using namespace std;

char str1[1000], str2[1000];

void mul(char *str1, char *str2)
{

int len1 = strlen(str1), len2 = strlen(str2);
int res[2000];
int i, j;
memset(res, 0, sizeof(res));

for(i = 0; i < len1; i++){
for(j = 0; j < len2; j++){
res[i + j] += (str1[i] - '0') * (str2[j] - '0');
}
}
int k = i + j - 2; //记录上面for循环中最后一次i+j的值
int goBit = 0; //进位
for(int i = k; i >= 0; i--){
res[i + 1] = (res[i] + goBit) % 10;
goBit = (res[i] + goBit) / 10;
}
if(goBit != 0){ //如果最后一次进位不为0
res[0] = goBit;
for(int i = 0; i <= k + 1; i++)
printf("%d", res[i]);
}else{
for(int i = 1; i <= k + 1; i++)
printf("%d", res[i]);
}
}

int main()
{

scanf("%s %s", str1, str2);
mul(str1, str2);
return 0;
}
Contents