Title Description
input
The first line of input contains the integer t (1 < = T < = 20), indicating the number of test cases. Then there are lines T, each containing two positive integers, A and B. note that integers are very large, which means that you should not use 32-bit integers to handle them. You can assume that the length of each integer does not exceed 1000
output
For each test Case, you should output two lines. The first line is "Case:", which represents the number of the test Case. The second line is the equation "A + B = Sum", which represents the result of A + B. Notice that there are some spaces in the equation. Output a blank line between two test cases.
Thinking analysis
It can be seen from the meaning of the question that the question requires the addition of two very large integers, so do not try to use long long int. the integers given by the question can no longer be represented by the data type of C + +, so consider the most general addition, one bit by one calculation, with the emphasis on: the standard number = (a + b + previous carry)% 10
Also pay attention to the output format. Blank lines only appear in the middle of two test cases, and there is no need to add blank lines after the last test case.
Code (AC capable)
#include<iostream> #include<cstring> using namespace std; char a[1010],b[1010],c[1010],d[1010]; int main() { int n,s,y=0; cin>>n; while(n--) { y++; cin>>a>>b; int s1=strlen(a); int t1=0; int s2=strlen(b); //Invert array a for(int i=s1-1;i>=0;--i) { c[t1]=a[i]; ++t1; } //Invert array b t1=0; for(int i=s2-1;i>=0;--i) { d[t1]=b[i]; ++t1; } //Find the maximum length of two numbers and fill in the same digits if(s1>s2) { s=s1; for(int i=s2;i<s1;++i) d[i]='0'; } else { s=s2; for(int i=s1;i<s2;++i) c[i]='0'; } //According to the addition rule, the standard number = (digit 1 + digit 2 + previous carry)% 10 int t=0,x1,x2; for(int i=0;i<s;++i) { x1=c[i]-'0'; x2=d[i]-'0'; d[i]=(x1+x2+t)%10+'0'; t=(x1+x2+t)/10; } //Judge whether there is carry in the highest position if(t==0) { cout<<"Case "<<y<<':'<<endl; cout<<a<<" + "<<b<<" = "; for(int i=s-1;i>=0;--i) cout<<d[i]; if(n!=0) cout<<endl<<endl; else cout<<endl; } else { cout<<"Case "<<y<<':'<<endl; cout<<a<<" + "<<b<<" = "; char c='1'; strcat(d,&c); for(int i=s;i>=0;--i) cout<<d[i]; if(n!=0) cout<<endl<<endl; else cout<<endl; } } return 0; }
If there is a better way, please comment