UstcOJ 1036 Long Sum

Description

A and B are both integers, which have at most 300 decimal digits. Please calculate their sum.

Input

Each line of the input contains two decimal integers A and B separated with a space character. (0<=A,B<10^300)

Output

For each line of input, print the value of A+B in decimal form on a line by itself.

Sample Input

1 1
1234567890 10000000010

Sample Output

2
11234567900

分析

兩個大整數(shù)相加,最多300位,先按字符串讀入,之后挨個字符轉(zhuǎn)化為數(shù)字相加,并進(jìn)位。最后如果哪個數(shù)有多余的數(shù),再加在一塊。

#include"stdio.h"
int main()
{
   char a[301],b[301];
   while(scanf("%s %s",a,b)!=EOF)
   {
      //printf("%s %s\n",a,b);
      int alength=0,blength=0;
      while(a[alength]!='\0')alength++;
      while(b[blength]!='\0')blength++;
      //printf("%d %d\n",alength,blength);

      int c[302];
      for(int i=0;i<302;i++)
      c[i]=0;
      int i=alength-1,j=blength-1,clength=0;
      while(i>=0&&j>=0)
      {
         int temp=a[i]-'0'+b[j]-'0'+c[clength];
         if(temp>=10) {c[clength]=temp%10;c[clength+1]=temp/10;}
         else c[clength]=temp;
         i--;
         j--;
         clength++;
      }
      while(i>=0)
      {
         int temp=a[i]-'0'+c[clength];
         if(temp>=10) {c[clength]=temp%10;c[clength+1]=temp/10;}
         else c[clength]=temp;
         i--;
         clength++;
      }
      while(j>=0)
      {
         int temp=b[j]-'0'+c[clength];
         if(temp>=10) {c[clength]=temp%10;c[clength+1]=temp/10;}
         else c[clength]=temp;
         j--;
         clength++;
      }
      if(c[clength]!=0)clength++;
      for(int k=clength-1;k>=0;k--)
      printf("%d",c[k]);
      printf("\n");
   }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,935評論 0 33
  • 變幻的人生和不變的人性 驢得水是今年看的第一部好片子,好到我到處給人推薦,好到到處去查影評,好到我為此寫一篇文章。...
    碎云閱讀 436評論 0 0
  • 出門在外久了與人打招呼常常多問一句你是哪里人,回答若是東北山東都會倍感親切。有人問過我,你一口東北味裝什么山東人啊...
    小董二閱讀 597評論 1 2

友情鏈接更多精彩內(nèi)容