A + B Problem II hd 1002

q923714892發表於2020-04-06
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

想法:因為大數在int或者__int64當中加減仍存在誤差,所以,我們將大數存在字串中,然後讓另一個陣列倒序儲存。然後將兩個陣列依次相加,如果大於9,進位。最後需要判斷最後一位是否為0,如果是0,不輸出最後一位,然後倒序輸出,如果是0,就直接倒序輸出。

 #include<stdio.h>  
#include<stdlib.h>  
#include<string.h>  
  
int max(int x,int y)  
{  
    int z;  
    z=x>y?x:y;//比較兩個值大小   
    return z;  
}  
  
int main()  
{  
    int lena,lenb,i,n,t=0,z,numa[1100],numb[1100];  
    char a[1100],b[1100];  
    scanf("%d",&n);  
    while(n--)  
    {  
        memset(numa,0,sizeof(numa));  
        memset(numb,0,sizeof(numb));//int陣列清零   
        scanf("%s%s",a,b);  
        lena=strlen(a);  
        lenb=strlen(b);  
        for(i=0;i<lena;i++)  
           numa[lena-1-i]=a[i]-'0';  
        for(i=0;i<lenb;i++)  
           numb[lenb-1-i]=b[i]-'0';  
        z=max(lena,lenb);  
        for(i=0;i<z;i++)//此處i值的範圍就是兩個字串長度的最大者  
        {  
            numa[i]=numa[i]+numb[i];  
            if(numa[i]>9)//處理相加大於十的情況  
            {  
                numa[i]=numa[i]-10;  
                numa[i+1]++;  
            }  
        }  
        t++;  
        printf("Case %d:\n",t);    
        printf("%s + %s = ",a,b);    
        if(numa[z]==0)// 判斷陣列第z位是否為零   
        {  
            for(i=z-1;i>=0;i--)  
               printf("%d",numa[i]);  
            printf("\n");  
        }  
        else  
        {  
            for(i=z;i>=0;i--)  
              printf("%d",numa[i]);  
            printf("\n");  
        }  
        if(n!=0)//每一次的輸入遇上一次的輸出之間空一行 ,n=0是輸出的是最後一組資料,即不用空出一行   
          printf("\n");  
    }  
    return 0;  
}  

相關文章