A + B Problem II(高精度的加法) c语言题解

题目如下:

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

output:

Case 1:
1 + 2 = 3

Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110

首先,这道题目要求输入的数可能有1000位,所以只能是以输入字符串的形式,将两个数输入到字符数组中。然后,再将两个数组从尾部开始,一个一个转为数字,再相加,将结果输进s[1050]中,(这里我们用memset先把s[]每个元素都初始化为0)如果两数之和>=10,则取(两数之和+s[m]即自己)对10的余数录进去,再使s[m+1]++.(前面要加上s[m]自己是因为可能它本身是1)

还有就是针对两者长度q,w不同的情况,分类讨论就行。  假设q>w,取q=15,w=6那么我们开始要分别从两个字符数组中的最后一个中取,即y[q-1]和t[w-1] (循环直到w-1==0为止,此时计算到s[6]) 然后,再用一个循环去输入y字符数组里面前q-w即9个的情况,因为可能s[7]为1,则s[7]+=y[8]可能为10(顶多为10了),则令s[7]=0,s[8]++

最后输出时,可能出现如999+1=1000的情况,所以取r=max{q,w},看s[r]是否为0,不为0则输出s[r]。然后再将s[r-1]至s[0]一个一个输出即可得到答案。

这题还有比较坑的一点是,题目要求output的每两个案例中有空行,而最后一个案例后面是没有空行的。

#include<stdio.h>
#include<math.h>
#include<string.h>
int main()
{ int c,s[1010];    int I=1;
 char y[1005],t[1005];
 scanf("%d",&c);
while(c--)
{  memset(s,0,sizeof(s));
    scanf("%s%s",&y,&t);int q=strlen(y),w=strlen(t);int i,j,m,u;
    printf("Case %d:\n%s + %s = ",I++,y,t);
 if(q>w) {for( i=w-1,m=0,u=q-1;  i>=0;   m++,u--,i--)
    {
       int a=y[u]-'0';int b=t[i]-'0';//这里是把字符转化为数字
        int n=s[m]; //记录原先的s[m]
        s[m]=(s[m]+a+b)%10;
        if(a+b+n>=10)s[m+1]++;
    }
    for( ;u>=0;u--,m++)
    {
        s[m]+=(y[u]-'0');
        if(s[m]==10){s[m]=0;s[m+1]++;}
    }
 }

 else  {for( i=q-1,m=0,u=w-1;   i>=0;  m++,u--,i--)
    {
       int a=y[i]-'0';int b=t[u]-'0';int n=s[m];
        s[m]=(a+b+s[m])%10;
        if(a+b+n>=10)s[m+1]++;
    }
    for( ;u>=0;u--,m++)
    {
        s[m]+=(t[u]-'0');
        if(s[m]==10){s[m]=0;s[m+1]++;}
    }
 }
 int r=(q+w+fabs(q-w))/2;//取两者最大
 if(s[r]!=0)printf("%d",s[r]);
  for(int p=r-1;p>=0;p--)
  {
      printf("%d",s[p]);
  }
  c!=0?printf("\n\n"):printf("\n");




}
return 0;
 }

        

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值