hdu 杭电 1002 A + B Problem II 果枫

题意:给你两个数,求和。很明显无论是int(最多能装10位的数),还是__int64(最多能装20位的数)都装不起1000位的数,所以必须用字符串装要相加的数。

解法:使用strrev()把字符串中的元素倒过来,如:a[3]="abc",strrev(a),数组a中的元素循序为"cba"

注意:输入的两个数都为0的情况,或一个数为0的情况。

ac代码:

View Code
#include <stdio.h>
#include<string.h>
int main()
{
    int t;
    char a[1020],b[1020],c[1020];
    int s,n;
    int i,j,k;
    while(scanf("%d",&t)!=EOF)
    {
        for(k=1;k<=t;k++)
        {
            scanf("%s",a);
            scanf("%s",b);
            printf("Case %d:\n%s + %s = ",k,a,b);

            if(a[0]=='0'&&b[0]=='0')
            {
                printf("0");
            }
            if(a[0]!='0'&&b[0]=='0')
            {
                printf("%s",a);
            }
            if(a[0]=='0'&&b[0]!='0')
            {
                printf("%s",b);
            }

            //两个数都为0的情况,或一个数为0的情况

            if(a[0]!='0'&&b[0]!='0') // 都不为0
            {

                memset(c,'0',sizeof(c));//c数组装加后的数
                strrev(a);strrev(b);//将数组a,b中的元素倒过来
                if(strlen(a)<strlen(b))
                {
                    s=strlen(b);
                    for(j=strlen(a);j<s;j++)
                    {
                        a[j]='0';
                    }
                }
                else
                {
                    s=strlen(a);
                    for(j=strlen(b);j<s;j++)
                    {
                        b[j]='0';

                    }
                }
                n=0;
                for(i=0;i<s;i++)
                {
                    c[i]=a[i]+b[i]+n-'0';
                    if(c[i]>'9')  //判断是否需要进位
                    {
                        n=1;
                        c[i]-=10;
                    }
                    else
                    {
                        n=0;
                    }
                }

                if(n==1)c[s]='1';//判断是否需要进位

                for(j=s;j>=0;j--)
                {
                    if(c[j]!='0')
                    {
                        i=j;
                        break;
                    }
                }
                for(;i>=0;i--)
                {
                    printf("%c",c[i]);
                }
            }   
            printf("\n");
            if(t!=k)printf("\n");
        }

    }

    return 0;
}



峰注:不明白请留言

原文地址:https://www.cnblogs.com/zgfailmr/p/2665885.html