C++如何通过栈实现超大整型数据的相加
前几天看《C++数据结构与算法》,文中有这样一句话:通过栈可以实现 非常大的数相加。假如要是将1234567890987654321和9876543210123456789这两个整型相加,是根本不可能的,因为整型都不能存储这些数。自己是个新手,并且感觉挺有兴趣的,就拿过来试试。
- 可以把超大整形看做是一个个字符
- 通过循环输入一个临时字符并将其压入栈中
- 通过从两个栈中弹出对应位的数字进行相加
- 通过一个整型栈来存取对应位运算后的数据
stack<char>p1,p2;
stack<int>re;
char tmp;
cout<<"welcome using the system!!!"<<endl;
cout<<"you can input any number if you want!!!\n";
cout<<endl;
cout<<"please input the first number(q as the end):\t";
cin>>tmp;
while(tmp!='q'){
p1.push(tmp);
cin>>tmp;
}
cout<<"please input the second number(q as the end):\t";
cin>>tmp;
while(tmp!='q'){
p2.push(tmp);
cin>>tmp;
}
cout<<"the input number has done!!!\n";
我创建了两个字符栈p1,p2,和一个字符tmp,循环输入tmp用来存储输入的字符,通过push()方法压入栈中,其中输入时,以‘q’字符结束。
这是我从书中截取栈工作的图片
源码
#include<iostream>
#include<stack>
#include<algorithm>
#include<functional>
using namespace std;
int main()
{
stack<char>p1;
stack<char>p2;
stack<int>re;
char tmp;
cout<<"welcome using the system!!!"<<endl;
cout<<"you can input any number if you want!!!\n";
cout<<endl;
cout<<"please input the first number(q as the end):\t";
cin>>tmp;
while(tmp!='q'){
p1.push(tmp);
cin>>tmp;
}
cout<<"please input the second number(q as the end):\t";
cin>>tmp;
while(tmp!='q'){
p2.push(tmp);
cin>>tmp;
}
cout<<"the input number has done!!!\n";
int tmp1=0,tmp2=0;
while((p1.size()!=0)&&(p2.size()!=0)){
int t1=p1.top();
int t2=p2.top();
tmp1=(t1-48)+(t2-48);
tmp1+=tmp2;
if(tmp1>9){
tmp2=tmp1/10;
tmp1%=10;
re.push(tmp1);
}
else{
re.push(tmp1);
tmp2=0;
}
p1.pop();
p2.pop();
}
if((p1.size()==0)&&(p2.size()!=0)){
while(p2.size()!=0){
int t1 =p2.top();
tmp1=t1-48;
re.push(tmp1);
p2.pop();
}
}
if((p1.size()!=0)&&(p2.size()==0)){
while(p1.size()!=0){
int t2=p1.top();
tmp1=t2-48;
re.push(tmp1);
p1.pop();
}
}
cout<<endl<<"the result is:\t";
while(re.size()!=0){
cout<<re.top();
re.pop();
}
cout<<endl<<endl;
return 0;
}
以前总是在网上搜别人的博客、资料,感觉写这个挺浪费时间的。忽然看到有个博主说,每个人都应该写一写:每个人不要只会向别人索取,更要记得奉献和分享。今天就试着写了第一篇,感觉写的挺认真的毕竟有很多不足,将就着看吧。