HDUOJ:大数相加3

该博客介绍了如何处理HDUOJ中关于大数相加的问题。博主分析了将大数视为字符串进行相加的策略,强调了处理进位的重要性,并提出将结果存储在二维数组中,按测试用例组织输出的方案。
摘要由CSDN通过智能技术生成

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=111111111111111110

我的分析:
1.大数相加问题,将大数a和大数b看作两个字符串,存入字符数组里,然后在新数组里对a,b数组每一项分别计算,注意进位的情况。
2.输入格式问题: 将结果另存在另一个二维数组,行数i代表Case i,列数代表结果

//1.第一次代码编译通过但结果显示不出来:
#include<stdio.h>
#include<string.h>
int main(void)
{
    int   casew,i,j=0,k;
    int   m=0,n=0,e;
    int   t,la,lb;
    char  a[22],b[22],c[22],w[22][22];
    scanf("%d",&casew);
    while (casew>=1){
    scanf("%s",a) ;
    scanf("%s",b) ;
    la = strlen(a)-1 ;
    lb = strlen(b)-1 ;
    t = la>lb?la:lb ;
    for(i=t ; i>=0 ;i--)
       c[i]=a[la--]-'\0';
    for(i=t ;i>=0 ; i--){
       c[i]+=b[lb--]-'\0';
       if(c[i]>10){
        c[i-1]++;
        c[i]-=10;
       }
     }
     for(e=0;e<=t;e++){
        w[m++][e]=c[e];
     }
        casew-- ;
   }
    for(k=0;k<casew;k++){
        printf("Case%d:",k+1);
        printf("%s + %s = ",a,b);
        for(e=0;e<=t;e++)
        printf("%d",w[k][e]);
        printf("\n");
    }

return 0 ;
}

//2.第二次错误:
#include<stdio.h>
#include<string.h>
int main() {
    int time,num=1;
    char stra[10000],strb[10000];
    int a[10000]={0},b[10000]={0},c[10000]={0};
    int i,j,k,h,lena,lenb,q;
    scanf("%d",&time);
    while(time--){
    scanf("%s",stra);
    scanf("%s",strb);
    lena=strlen(stra)-1;
    lenb=strlen(strb)-1;
    for(i=lena;i>=0;i--)
        a[i]=stra[i]-'\0';
    for(j=lenb;j>=0;j--)
        b[j]=strb[j]-'\0';
    q=lena>lenb?lena:lenb;
        for(k=q;k>=0;k--){
           c[k]=a[k]+b[k];
           if(c[k]>=10)
           {
               c[k]=(a[k]+b[k])%10;
               c[k-1]++;
           }
        }
    printf("Case%d:\n",num);
    num++;
    printf("%s + %s =",stra,strb);
    for(h=0;h<=q;h++)
        printf("%d",c[h]);
        printf("\n");
    if(time>=1)
        printf("\n");
    }
    return 0;
}

//待续

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值