字符串模擬大數相加

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
using namespace std;
const int maxn=100009;
char s1[maxn];
char s2[maxn];
char temp1[maxn];
char temp2[maxn];
char sum[maxn+2];
int main()
{
    int t;
    scanf("%d",&t);
     for(int k=1;k<=t;k++)
     {
        scanf("%s%s",s1,s2);
        printf("Case %d:\n",k);
        printf("%s + %s = ",s1,s2);
        int len1 = 0;
        int len2 = 0;
        int i = 0;
        int j = 0;
        int maxLen = 0;
        int nSum = 0;
        int nNextBit = 0;
        int nOverFlow = 0;
        len1=strlen(s1);
        len2=strlen(s2);
        memset(temp1,'0',sizeof(temp1));
        memset(temp2,'0',sizeof(temp2));
        j=0;
        for(i=len1-1;i>=0;i--)
        temp1[j++]=s1[i];

        j=0;
        for(i=len2-1;i>=0;i--)
        temp2[j++]=s2[i];
        //temp2[j]='\0';
         maxLen=(len1>len2)? len1:len2;
//        for( i=0;i<maxLen;i++)
//        printf("%c",temp1[i]);
//
//     printf("\n");
//     for(int j=0;j<maxLen;j++)
//     printf("%c",temp2[j]);
       for(i=0;i<maxLen;i++)
       {
           nSum=temp1[i]-'0'+temp2[i]-'0'+nNextBit;
           if(nSum>9)
           {
               if(i==(maxLen-1))
               {
                   nOverFlow=1;
               }
               nNextBit=1;
               sum[i]=nSum-10+'0';
           }
           else
           {
               nNextBit=0;
               sum[i]=nSum+'0';
           }
       }
       if(nOverFlow==1)
        sum[maxLen++]=nOverFlow+'0';
        sum[maxLen]='\0';
        for(i=maxLen-1;i>=0;i--)
        putchar(sum[i]);
        printf("\n");
        if(k!=t)
        printf("\n");

    }
    return 0;
}

發佈了65 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章