UVa 10106 Product

高精度乘法问题解决
本文介绍了一种解决高精度乘法问题的方法,通过使用字符数组存储大整数,并实现了一个高精度乘法的算法。文章包含完整的AC代码示例,并特别注意处理结果可能为0的特殊情况。

高精度乘法问题,WA了两次是因为没有考虑结果为0的情况。



 Product 

 

 

The Problem

The problem is to multiply two integers X, Y. (0<=X,Y<10250)

The Input

The input will consist of a set of pairs of lines. Each line in pair contains one multiplyer.

The Output

For each input pair of lines the output line should consist one integer the product.

Sample Input

 

12
12
2
222222222222222222222222

 

Sample Output

 

144
444444444444444444444444

AC代码:

 1 //#define LOCAL
 2 #include <iostream>
 3 #include <cstdio>
 4 #include <cstring>
 5 using namespace std;
 6 
 7 const int maxn = 265;
 8 char a[maxn], b[maxn];
 9 int x[maxn], y[maxn], mul[maxn * 2 + 10];
10 void Reverse(char s[], int l);
11 
12 int main(void)
13 {
14     #ifdef LOCAL
15         freopen("10106in.txt", "r", stdin);
16     #endif
17 
18     while(gets(a))
19     {
20         gets(b);
21         int la = strlen(a);
22         int lb = strlen(b);
23         memset(mul, 0, sizeof(mul));
24         memset(x, 0, sizeof(x));
25         memset(y, 0, sizeof(y));
26         Reverse(a, la);
27         Reverse(b, lb);
28         int i, j;
29         for(i = 0; i < la; ++i)
30             x[i] = a[i] - '0';
31         for(i = 0; i < lb; ++i)
32             y[i] = b[i] - '0';
33 
34         for(i = 0; i < lb; ++i)
35         {
36             int s = 0, c = 0;
37             for(j = 0; j < maxn; ++j)
38             {
39                 s = y[i] * x[j] + c + mul[i + j];
40                 mul[i + j] = s % 10;
41                 c = s / 10;
42             }
43         }
44 
45         for(i = maxn * 2 + 9; i >= 0; --i)
46             if(mul[i] != 0)
47                 break;
48         if(i < 0)
49             cout << 0;
50         else
51         {
52             for(; i >=0; --i)
53                 cout << mul[i];
54         }
55         cout << endl;
56     }
57     return 0;
58 }
59 //用来反转数组
60 void Reverse(char s[], int l)
61 {
62     int i;
63     char t;
64     for(i = 0; i < l / 2; ++i)
65     {
66         t = s[i];
67         s[i] = s[l - i -1];
68         s[l - i -1] = t;
69     }
70 }
代码君

 

转载于:https://www.cnblogs.com/AOQNRMGYXLMV/p/3817598.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值