大数的加法 进位
发布时间:2020-12-14 03:03:19 所属栏目:大数据 来源:网络整理
导读:/*author:jzdate:2014 09 01*//*题目描述:实现一个加法器,使其能够输出a+b的值。输入:输入包括两个数a和b,其中a和b的位数不超过1000位。输出:可能有多组测试数据,对于每组数据,输出a+b的值。样例输入:2 610000000000000000000 100000000000000000000
/* author:jz date:2014 09 01 */ /* 题目描述: 实现一个加法器,使其能够输出a+b的值。 输入: 输入包括两个数a和b,其中a和b的位数不超过1000位。 输出: 可能有多组测试数据,对于每组数据, 输出a+b的值。 样例输入: 2 6 10000000000000000000 10000000000000000000000000000000 样例输出: 8 10000000000010000000000000000000 来源: 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; else flag=0; st1.pop(); } while (!st2.empty()) { res.push( (st2.top()+flag)%10); if ( (st2.top()+flag)>=10)//进位标志 flag=1; else flag=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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |