ZOJ 1205 Martian Addition

来源:互联网 发布:淘宝app首页 编辑:程序博客网 时间:2024/06/01 09:31
Martian Addition

Time Limit: 2 Seconds      Memory Limit: 65536 KB

  In the 22nd Century, scientists have discovered intelligent residents live on the Mars. Martians are very fond of mathematics. Every year, they would hold an Arithmetic Contest on Mars (ACM). The task of the contest is to calculate the sum of two 100-digit numbers, and the winner is the one who uses least time. This year they also invite people on Earth to join the contest.
  As the only delegate of Earth, you're sent to Mars to demonstrate the power of mankind. Fortunately you have taken your laptop computer with you which can help you do the job quickly. Now the remaining problem is only to write a short program to calculate the sum of 2 given numbers. However, before you begin to program, you remember that the Martians use a 20-based number system as they usually have 20 fingers. 

Input:
You're given several pairs of Martian numbers, each number on a line. 
Martian number consists of digits from 0 to 9, and lower case letters from a to j (lower case letters starting from a to present 10, 11, ..., 19). 
The length of the given number is never greater than 100.

Output:
For each pair of numbers, write the sum of the 2 numbers in a single line.

Sample Input:
1234567890abcdefghij99999jjjjj9999900001

Sample Output:
bdfi02467jiiiij00000
题意:相当于大数相加,逢20进1
注意:像00001这样前面有0的情况,0不能输出,但是0+0=0这样的情况,0要保留
代码:
#include<string.h> #include<iostream> #include<stdio.h> using namespace std; #define N 110 char str[N],sbr[N],t[N]; int a[N],b[N],c[N]; int main() {     int i,j,k,len1,len2,len;     while(cin>>str>>sbr)     {         memset(c,0,sizeof(c));         memset(a,0,sizeof(a));         memset(b,0,sizeof(b));         len1=strlen(str);         len2=strlen(sbr);         len=len1>len2?len1:len2;         i=0;         for(j=len1-1;j>=0;j--)         {             if(str[j]<='9'&&str[j]>='0')                 a[i++]+=str[j]-'0';             else             a[i++]+=str[j]-87;         }         i=0;         for(j=len2-1;j>=0;j--)         {             if(sbr[j]<='9'&&sbr[j]>='0')             b[i++]+=sbr[j]-'0';             else             b[i++]+=sbr[j]-87;         }         for(i=0;i<len;i++)         {             c[i]+=(a[i]+b[i]);             if(c[i]>19)             {                 c[i+1]=c[i]/20; //注意这里进位时与乘法进位相同                 c[i]%=20;             }         }         i=len;         int flag=1;         while(!c[i])         {             i--;             if(i==-1)             {                 cout<<"0"<<endl; //零的输出                 flag=0;                 break;             }         }         if(!flag) continue;         k=0;         for(j=i;j>=0;j--)         {             if(c[j]>=0&&c[j]<=9)             t[k++]=(c[j]+'0');             else             t[k++]=(c[j]+87);         }         for(j=0;j<k;j++)         cout<<t[j];         cout<<endl;      }     return 0; }


原创粉丝点击