加入收藏 | 设为首页 | 会员中心 | 我要投稿 辽源站长网 (https://www.0437zz.com/)- 云专线、云连接、智能数据、边缘计算、数据安全!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2021-03-14 16:34:47 所属栏目:大数据 来源:网络整理
导读: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 no

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

   
   
    
    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就可以了

(编辑:辽源站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读