菜鸟上路,杭电OJ1002之大数相加

来源:互联网 发布:与大数据相关的技术 编辑:程序博客网 时间:2024/05/21 03:17
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.
 

Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line is the an equation "A + B = Sum", Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.
 

Sample Input
21 2112233445566778899 998877665544332211
 

Sample Output
Case 1:1 + 2 = 3Case 2:112233445566778899 + 998877665544332211 = 1111111111111111110






















刚开始想用数组做,后来想到了栈,瞬间简化了不少,数据结构的正确选择还是很重要的!!




我的代码:




#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]!='\0')            A.push(s1[i++]);        i=0;        while(s2[i]!='\0')            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就可以了




















0 0
原创粉丝点击