C++如何通过栈实现超大整型数据的相加
来源:互联网 发布:怎样正确使用网络 编辑:程序博客网 时间:2024/05/01 23:24
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;}
以前总是在网上搜别人的博客、资料,感觉写这个挺浪费时间的。忽然看到有个博主说,每个人都应该写一写:每个人不要只会向别人索取,更要记得奉献和分享。今天就试着写了第一篇,感觉写的挺认真的毕竟有很多不足,将就着看吧。
1 0
- C++如何通过栈实现超大整型数据的相加
- Java实现超大数字相加的算法
- C语言中如何实现对超大数据的存取与运算
- 两个超大整数相加(c++)
- C语言超大数相加
- 通过Callable,Future实现十亿数据的并行相加
- 两个超大数的相加
- 用栈实现整型数据的四则运算
- java如何对两个超大数相加
- 一个实现长整型数相加减的小程序
- 一个实现长整型数相加减的小程序
- 两个超大整数相加之数组实现
- 如何实现快速地从超大数据库中提取数据并进行相关的操作
- C语言实现大整型数据乘法
- 通过移位的方式实现相加算法
- 如何检测整型相加溢出(overflow)
- 用栈实现的整型数据的四则运算
- C 语言 超大数相加和求余
- Glide深入浅出(一)——Glide vs Picasso
- 《算法入门竞赛经典》(第八章)8.1
- 导入项目运行报错:某些输入文件使用或覆盖了已过时的 API……
- android 图片压缩的三种方法,其实还有第四种就是2.2以后提供的压缩类
- 3DES 和 ECB CBC 加密方式
- C++如何通过栈实现超大整型数据的相加
- PHP[杂项函数] - define()
- ruby获取本机mac加密生成lisence文件,客户端根据lisence许可调用主程序
- 摄像机标定过程中常用坐标系及其关系
- spring 与 springMVC的几个注解
- c++各种排序效率相比较
- linux 技巧:使用 screen 管理你的远程会话
- 建议116:避免用非对称算法加密文件
- http请求头