菜鸟上路,杭电OJ1002之大数相加
Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow,each line consists of two positive integers,A and B. Notice that the integers are very large,that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.
2 1 2 112233445566778899 998877665544332211? Sample Output Case 1: 1 + 2 = 3 Case 2: 112233445566778899 + 998877665544332211 = 2222222222222221110 刚开始想用数组做,后来想到了栈,瞬间简化了不少,数据结构的正确选择还是很重要的!! 我的代码: #include <iostream> #include <stack> #include <string> using namespace std; int main() { string s1,s2; int n; int i=0; int j=1; cin>>n; stack<char> A; stack<char> B; stack<char> C; int c=0; int num=0; while(n--) { c=0; i=0; cin>>s1; cin>>s2; while(!A.empty()) A.pop(); while(!B.empty()) B.pop(); if(j!=1) cout<<endl; while(s1[i]!=' ') A.push(s1[i++]); i=0; while(s2[i]!=' ') B.push(s2[i++]); while(!A.empty()||!B.empty()) { if(!A.empty()&&B.empty()) { num=A.top()-'0'+c; A.pop(); } else if(A.empty()&&!B.empty()) { num=B.top()-'0'+c; B.pop(); } else if(!A.empty()&&!B.empty()) { num=A.top()-'0'+B.top()-'0'+c; A.pop(); B.pop(); } if(num >=10) { c=1; C.push(num%10+'0'); } else { c=0; C.push(num+'0'); } } /*if(C.top()=='0') C.push('1');*/ cout<<"Case "<<j++<<":"<<endl; cout<<s1<<" + "<<s2<<" = "; while(!C.empty()) { cout<<C.top(); C.pop(); } cout<<endl; } }注意:题目要求输出的两个结果之间应当有一个空行,但是这并不代表我们就可以在代码的最后写cout<<endl<<endl;这样的表述,这会导致PE错误! 正确的做法是: if(j!=1) cout<<endl; 再在代码最后来一个endl就可以了 (编辑:开发网_开封站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |