菜鸟上路,杭电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.
 

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 = 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值