Hang Dian OJ1002 Question A+B

Situation analysis

  1. The first case: the two digits are the same
    • The two digits are the same and the digits remain the same after addition, for example: 22+33=55;
    • Two digits are the same and add 1 to the digit after adding, for example: 999+999=1998;
  2. The second case: the two digits are different
    • The result digit is equal to max (the digit of the larger digit), for example: 123+1=124;
    • The number of result bits is equal to max+1, for example, 999+1=1000;
#include <stdio.h>
#include <string.h>

//字符转整型函数
int CharToInt(char ch){
    
    
    return (ch-'0');
}

int main(){
    
    
	//用两个字符数组存储两个大数
    char a[1000],b[1000];
   //num[1001]用来存放结果,因为结果位数有可能会比位数最长的那个数的位数大1,所以多数组长度大1
    int num[1001];
    //n即总共有n组数,al为数组a的长度,bl为数组b的长度
    int n,i,j=1,al,bl;
    //k跟t用来记录结果数组的长度
    int k,t;
    scanf("%d",&n);
    while (n--) {
    
    
    //j用来标识是哪一组大数,并且每结束一组大数的运算都要输出回车
        if(j!=1)
            printf("\n");
        scanf("%s",a);
        al=(int)strlen(a);
        scanf("%s",b);
        bl=(int)strlen(b);
        k=al>bl?al:bl;
        t=k;
        for(i=0;i<=k;i++)
            num[i]=0;
        for(;al>0&&bl>0;k--){
    
    
            num[k]+=CharToInt(a[--al])+CharToInt(b[--bl]);
            if(num[k]/10){
    
    
                num[k-1]++;
                num[k]%=10;
            }
        }
        while (al>0) {
    
    
            num[k--]+=CharToInt(a[--al]);
            if(num[k+1]/10){
    
    
                num[k]++;
                num[k+1]%=10;
            }
        }
        while (bl>0) {
    
    
            num[k--]+=CharToInt(b[--bl]);
            if(num[k+1]/10){
    
    
                num[k]++;
                num[k+1]%=10;
            }
        }
        printf("Case %d:\n",j++);
        printf("%s + %s = ",a,b);
        for(i=0;i<=t;i++)
        {
    
    
            if(i==0&&num[i]==0)
                i++;
            printf("%d",num[i]);
        }
        printf("\n");
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_45465526/article/details/103941298