大数相乘(2016网易内推第一场编程题)

发现很多都喜欢考大数相乘,大数想除什么的。这个方法用的模拟乘法,移位运算。

 1 //大数字相乘
 2 
 3 #include "iostream"
 4 #include "string.h"
 5 #include "vector"
 6 #define MAX 201
 7 using namespace std;
 8 
 9 char a[MAX], b[MAX];
10 int ans[MAX] = {0};
11 int n,m;
12 
13 int main()
14 {
15     while (cin >> a >> b)
16     {
17         n = strlen(a);
18         m = strlen(b);
19         memset(ans, 0, MAX);
20 
21         for (int i = n - 1; i >= 0; i--)
22         {
23             for (int j = m - 1; j >= 0; j--)
24             {
25                 ans[1 + i + j] += (int)(a[i] - '0')*(int)(b[j] - '0');
26             }
27         }
28 
29         for (int i = m + n - 1; i > 0; i--)
30         {
31             if (ans[i] >= 10)
32             {
33                 ans[i - 1] += ans[i] / 10;
34                 ans[i] %= 10;
35             }
36         }
37         bool tag = false;//出现过非0数字
38         for (int i = 0; i < m + n - 1; i++)
39         {
40             if (ans[i] != 0)
41                 tag = true;
42             if (!tag&&ans[0] == 0 && ans[i] == 0 && i != m + n - 1)
43                 continue;
44             if(tag)
45             cout << ans[i];//防止全0情况。
46         }
47         cout << ans[m + n - 1];
48             
49         cout << endl;
50     }
51 
52 
53     system("pause");
54 }
原文地址:https://www.cnblogs.com/SeekHit/p/5802570.html