A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 9348 Accepted Submission(s): 1557
Problem Description
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
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>
using namespace std;
#define Base 10
#define MaxLen 1000
struct BigInt {
int len;
int data[MaxLen];
BigInt() :len(0) {}
BigInt(const BigInt& s) :len(s.len){
memcpy(this->data,s.data,len*sizeof(*data));
}
BigInt(int s) :len(0){
for(;s>0;s=s/Base)
data[len++]=s%Base;
}
BigInt & operator = (const BigInt& s){
this->len=s.len;
memcpy(this->data,s.data,len*sizeof(*data));
return *this;
}
int& operator [](int index){ return data[index]; }
int operator [](int index) const { return data[index]; }
};
BigInt operator + (BigInt & a, BigInt & b){
BigInt c;
int i,carry=0;
c.len=a.len>b.len?a.len:b.len;
for(i=0;i<c.len||carry>0;++i){
if(i<a.len) carry+=a[i];
if(i<b.len) carry+=b[i];
c[i]=carry%Base;
carry/=Base;
}
c.len=i;
return c;
}
istream & operator >> (istream & is, BigInt & s)
{
int i;
char ch[MaxLen];
is>>ch;
s.len=strlen(ch);
for(i=s.len-1;i>-1;--i)
s[i]=ch[s.len-1-i]-'0';
return is;
}
ostream & operator << (ostream & os, BigInt & s)
{
int i;
for(i=s.len-1;i>-1;--i)
os<<s[i];
return os;
}
int main () {
int n,i;
BigInt a,b,c;
cin>>n;
for(i=1;i<n;++i){
cin>>a>>b;
c=a+b;
cout<<"Case "<<i<<":"<<endl;
cout<<a<<" + "<<b<<" = "<<c<<endl<<endl;
}
cin>>a>>b;
c=a+b;
cout<<"Case "<<i<<":"<<endl;
cout<<a<<" + "<<b<<" = "<<c<<endl;
return 0;
}
此处需注意输出的问题,即最后一组A+B不用输出2个换行符(仔细看题),否则PE。