HD 1002 A+B问题 大数相加


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
 

Author
Ignatius.L
 

这道题的整体思想用到了小学两数相加的计算公式。例如 123和234相加

                                                                

                                                     1   2    3
                                             +      4   5    6
                                                     5   7    9

我们在计算时先计算个位再计算十位最后计算百位,每次相加后都会看看会不会进位会的话再接下来的计算正进行进位。通过这种思想,我们把两个大数相加看做一个个小的数相加,逐一计算,通过用字符串数组来存储。例如 1 2 3与4 5 6 分别代表字符串1 2 3和4 5 6,先将3和6转化为数字,求和后判断是否进位,最后取余数得9,再将余数转化成字符9存进另一个字符串中,依次类推计算完为止。

 
#include<stdio.h>
#include<string.h>
int main()
{
    int n,j,i,k,m=0;//m用来判断是否要换行。
    char a[1000],b[1000],c[1000],d[1000],e[1001];//定义五个字符串数组来存储和接收字符串
    scanf("%d ",&n);
    int s=n;
    while(n--)
   {  m++;
       k=0;
   for(i=0;i<1000;i++)//给a,b,c,d都赋初值'0',
   {
     a[i]='0';
     b[i]='0';
     c[i]='0';
     d[i]='0';
   }
    for(i=0;i<1001;i++)//给e赋初值'0',因为e是用来存储结果的,两个1000位的数相加最多不超过1001位。
    e[i]='0';
    scanf("%s",a);
    scanf("%s",b);
    for(i=999,j=1;i>=1000-strlen(a);i--,j++)//逆序给c,d数组赋值以符合我们加减法计算的习惯。方便后面计算。
    {
        c[i]=a[strlen(a)-j];
    }
    for(i=999,j=1;i>=1000-strlen(b);i--,j++)
    {
        d[i]=b[strlen(b)-j];
    }
    int l=(1000-strlen(a))<(1000-strlen(b))?(1000-strlen(a)):(1000-strlen(b));//找到位数较多的数组,因为是你徐赋值的所以找到下标较小的数组。
    for(i=1000;i>=l;i--)//例如:00123,01234两个数下标最小的是第二个数组的第二个,因为两个数相加有可能要进位,所以多留一位出来所以用1000。
    {  
        int x=c[i-1]-48;//先将要计算的两个字符变为数字,
        int y=d[i-1]-48;
        int sum=x+y+k;//k代表进几位
        if(sum>=10) //判断是否进位
        {
            k=1;
            sum=sum%10;//求出应存在该位置上的数字
        }
        else
        {
            k=0;
        }
        e[i]=sum+48;//再将改数字转化为字符存入该字符串。
    }
    printf("Case %d:\n",m);
    printf("%s",a);printf(" + ");printf("%s",b);printf(" = ");
   for(i=l;i<1001;i++)
   {
       if(i==l&&e[i]=='0')continue;
        printf("%c",e[i]);
    }printf("\n");
    if(m!=s)printf("\n");//每组数据之间换行。
   }return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41661918/article/details/79943456
今日推荐