大数的加法 进位

来源:互联网 发布:python .shift 编辑:程序博客网 时间:2024/06/11 09:47
/*author:jzdate:2014 09 01*//*题目描述:实现一个加法器,使其能够输出a+b的值。输入:输入包括两个数a和b,其中a和b的位数不超过1000位。输出:可能有多组测试数据,对于每组数据,输出a+b的值。样例输入:2 610000000000000000000 10000000000000000000000000000000样例输出:810000000000010000000000000000000来源:2010年华中科技大学计算机研究生机试真题答疑:解题遇到问题?分享解题心得?讨论本题请访问:http://t.jobdu.com/thread-7921-1-1.html*/#include<iostream>using namespace  std;#include<stack>#include<queue>#include <string>void Bigdata_addition(){stack<int> st1;stack<int> st2;stack<int> res;string s1,s2;int flag;while(cin>>s1){flag=0;//进位标志cin>>s2;//cout<<s1<<endl;//cout<<s2<<endl;int s1len=s1.length();int s2len=s2.length();/*if (){}*/for(int i1=0;i1<s1len;i1++)st1.push(s1[i1]-48);for(int i2=0;i2<s2len;i2++)st2.push(s2[i2]-48);while (!st1.empty()&&!st2.empty()){int a=st1.top();//cout<<"a"<<a<<endl;int b=st2.top();//cout<<"b"<<b<<endl;//cout<<a+b;res.push( (a+b+flag)%10 );if ( (a+b+flag)>=10)//进位标志 flag=1;else flag=0;st1.pop();st2.pop();}while (!st1.empty()){res.push( (st1.top()+flag)%10 );if ( (st1.top()+flag)>=10)//进位标志flag=1;elseflag=0;st1.pop();}while (!st2.empty()){res.push( (st2.top()+flag)%10);if ( (st2.top()+flag)>=10)//进位标志flag=1;elseflag=0;st2.pop();}if (1==flag){res.push(1);}while (!res.empty()){cout<<res.top();res.pop();}cout<<endl;}}int main(){Bigdata_addition();return 0;}

0 0
原创粉丝点击