HDU-1002-A + B Problem II(高精度加法)
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
InputThe 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.
OutputFor 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
高精度加法模板,注意前导0不输出。
1 // 高精度加法 2 #include<iostream> 3 #include<cstring> 4 using namespace std; 5 int a[1005],b[1005]; 6 7 int pluss(int a[],int b[]){ 8 int l; 9 l=a[0]>b[0]?a[0]:b[0]; 10 for(int i=1;i<=l;i++){ 11 a[i+1]+=(a[i]+b[i])/10; 12 a[i]=(a[i]+b[i])%10; 13 } 14 if(a[l+1]>0) a[0]=l+1; 15 else a[0]=l; 16 return 0; 17 } 18 19 int main(){ 20 int T; 21 scanf("%d",&T); 22 for(int cnt=1;cnt<=T;cnt++){ 23 24 //读入 25 memset(a,0,sizeof(a)); 26 memset(b,0,sizeof(b)); 27 string s1,s2; 28 cin>>s1>>s2; 29 a[0]=s1.length(); 30 b[0]=s2.length(); 31 for(int i=1;i<=a[0];i++){ 32 a[i]=s1[a[0]-i]-'0';//倒序存储 33 } 34 for(int i=1;i<=b[0];i++){ 35 b[i]=s2[b[0]-i]-'0'; 36 } 37 38 cout<<"Case "<<cnt<<":"<<endl<<s1<<" + "<<s2<<" = "; 39 40 pluss(a,b); 41 42 int flag=0; 43 for(int i=a[0];i>=1;i--){ 44 if(flag==0&&a[i]==0) continue;//坑点:前导0不输出。 45 else{ 46 cout<<a[i]; 47 flag=1; 48 } 49 } 50 51 cout<<endl; 52 if(cnt!=T) cout<<endl; 53 54 } 55 return 0; 56 }