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

分析

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

#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");
   }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

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