//此題重在理解兩個數(shù)相乘的算法,
4
#include <stdio.h>
5
#include <stdlib.h>
6
#include <string.h>
7
#define MAXSIZE 201
8
int main()
9

{
10
char line1[MAXSIZE];
11
char line2[MAXSIZE];
12
int a1[MAXSIZE];
13
int a2[MAXSIZE];
14
int product[MAXSIZE];
15
16
while ( scanf ("%s%s", line1, line2) != EOF )
17
{
18
int len1, len2;
19
len1 = strlen (line1);
20
len2 = strlen (line2);
21
22
memset (a1, 0, sizeof (a1));
23
memset (a2, 0, sizeof (a2));
24
memset (product, 0, sizeof (product));
25
26
//對負數(shù)的處理
27
if ( line1[0] == '-' || line2[0] == '-' )
28
return 0;
29
//對 0 和 其它數(shù)相乘的處理
30
int mark = 0;
31
if ( ( !strcmp (line1,"0") ) || ( !strcmp (line2, "0") ) )
32
{
33
printf ("%d", 0);
34
}
35
36
//將字符數(shù)轉(zhuǎn)化為數(shù)字
37
int j = 0;
38
for (int i = len1 - 1; i >= 0; i--)
39
{
40
a1[j++] = line1[i] - '0';
41
}
42
int k = 0;
43
for (int i = len2 - 1;i >= 0; i--)
44
{
45
a2[k++] = line2[i] - '0';
46
}
47
48
//乘法算法
49
for (int i = 0; i < len2; i++)
50
for (int j = 0; j < len1; j++)
51
{
52
product[i + j] += a1[j] * a2[i];
53
}
54
55
//處理進位
56
for (int i = 0; i < MAXSIZE; i++ )
57
{
58
if ( product[i] >= 10 )
59
{
60
product [i + 1] += product [i] / 10;
61
product [i] = product[i] % 10;
62
}
63
}
64
65
//輸出處理
66
bool target = false;
67
for (int i = MAXSIZE - 1; i >= 0; i--)
68
{
69
if (target)
70
printf ("%d", product[i]);
71
else if (product[i])
72
{
73
printf ("%d", product[i]);
74
target = true;
75
}
76
}
77
printf ("\n");
78
}
79
//system ("pause");
80
return 0;
81
}
82
以及特殊數(shù)據(jù)的考慮 :如 含有 0 和 負數(shù)時
posted on 2010-08-09 13:08
雪黛依夢 閱讀(403)
評論(0) 編輯 收藏 引用 所屬分類:
大數(shù)