A + B Problem II

Problem Description
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.
 
Code
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
    int i=1,j,t,lena,lenb,len;
    int a[1000],b[1000],sum[1001];
    char str1[1000],str2[1000];
    scanf("%d",&t);
    while(i<=t)
    {
        memset(a,0,sizeof(a));
        memset(b,0,sizeof(b));
        memset(sum,0,sizeof(sum));//a、b数组置零
        scanf("%s%s",&str1,&str2);
        lena=strlen(str1);
        lenb=strlen(str2);
        for(j=0;j<lena;j++)
        {
            a[lena-1-j]=str1[j]-'0';
        }
        for(j=0;j<lenb;j++)
        {
            b[lenb-1-j]=str2[j]-'0';
        }
        len=lena>lenb ? lena:lenb;    
        for(j=0;j<len;j++)
        {
            sum[j]=sum[j]+a[j]+b[j];
            if(sum[j]>9)//处理相加大于十的情况 
            {
                sum[j]=sum[j]-10;
                sum[j+1]++; 
            }
        }
        if(sum[len]==0) 
        {
            printf("Case %d:\n",i);
            printf("%s + %s = ",str1,str2);
            for(j=len-1;j>=0;j--)
                printf("%d",sum[j]);
            if(i!=t)
                printf("\n\n");
            else 
                printf("\n");
        }
        else 
        {
            printf("Case %d:\n",i);
            printf("%s + %s = ",str1,str2);
            for(j=len;j>=0;j--)
                printf("%d",sum[j]);
            if(i!=t)
                printf("\n\n");
            else 
                printf("\n");
        }
        i++;
    }
    return 0;
}

Attention
void *memset(void *s, int ch, size_t n);
函数解释:将s中当前位置后面的n个字节 (typedef unsigned int size_t )用 ch 替换并返回 s 。
memset:作用是在一段内存块中填充某个给定的值,它是对较大的结构体数组进行清零操作的一种最快方法。
 
extern unsigned int strlen(char *s);
头文件:string.h
格式:strlen (字符数组名)
功能:计算给定字符串的(unsigned int型)长度,不包括'\0'在内
说明:返回s的长度,不包括结束符NUL。
 

posted on 2018-07-22 16:43  Joanna_zero  阅读(408)  评论(0编辑  收藏  举报

导航