高精度大整数加法

今天偶然在逛网页时,发现了这题。之前在算法书上也有看到,不过还是觉得这个解法更简单,易于理解。附上代码,大家多多交流。O(∩_∩)O哈哈~

此方法采用栈的结构来存储加数(栈1、栈2)和结果(栈3)。

1.用字符数组存储输入的加数,一位位存入栈(栈1、栈2)中,这样栈顶元素是最低位。

2.将两个栈(栈1、栈2)元素出栈相加,结果存入栈3中,并保存进位。(此时,栈3的栈顶元素为最高位)

3.处理栈1、栈2中剩下的元素。

4.栈3出栈,输出结果

高精度大整数加法
 1 #include <iostream>
2 #include <stack>
3 using namespace std;
4
5 stack<int>s1;
6 stack<int>s2;
7 stack<int>s3;
8 char c1[100];
9 char c2[100];
10
11 void LargeIntAdd()
12 {
13 int len1 = strlen(c1);
14 int len2 = strlen(c2);
15 int i;
16 for(i=0;i<len1;i++)
17 {
18 s1.push(c2[i]-'0'); //将输入的数据(高位到低位)存入s1栈中,此时栈顶为最低位
19 }
20
21 for(i=0;i<len2;i++)
22 {
23 s2.push(c2[i]-'0'); //将输入的数据(高位到低位)存入s2栈中,此时栈顶为最低位
24 }
25
26 int tmp = 0;
27 while(!s1.empty() && !s2.empty() ) //若两个栈都不为空
28 {
29 //将栈1、栈2均pop出栈做加法,并考虑进位,结果入栈3,这时栈3正好是低位入栈
30 tmp += s1.top()+s2.top();
31 s1.pop();
32 s2.pop();
33 s3.push(tmp%10);
34 tmp=tmp/10;
35 }
36 while(!s1.empty()) //s1栈不为空
37 {
38 tmp += s1.top();
39 s1.pop();
40 s3.push(tmp%10);
41 tmp=tmp/10;
42 }
43 while(!s2.empty()) //s2栈不为空
44 {
45 tmp += s2.top();
46 s2.pop();
47 s3.push(tmp%10);
48 tmp=tmp/10;
49 }
50 if(tmp) //若进位不为0,入栈
51 {
52 s3.push(tmp);
53 }
54 while(!s3.empty()) //最终的结果(栈顶为最高位)输出
55 {
56 cout<<s3.top();
57 s3.pop();
58 }
59 cout<<endl;
60
61 }
62 int main()
63 {
64 cout<<"请输入第一个数:";
65 cin>>c1;
66 cout<<"请输入第二个数:";
67 cin>>c2;
68 cout<<"输出最终结果是:";
69 LargeIntAdd();
70 return 0;
71 }

原文地址:https://www.cnblogs.com/chenbin7/p/2199291.html