ZOJ1205

Description

  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: 

1234567890
abcdefghij
99999jjjjj
9999900001
Sample Output: 
bdfi02467j
iiiij00000

思路

20进制的大数加法

代码

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define MAX 1000
using namespace std;
int Addition(char num1[],char num2[],int sum[])
{
    int i,j,len;
    int n2[MAX]={0};
    int len1=strlen(num1);
    int len2=strlen(num2);
    len=max(len1,len2);
    for(i=len1-1,j=0;i>=0;i--,j++)
    {
       if(num1[i]>='0'&&num1[i]<='9')
          sum[j]=num1[i]-'0';
       else
          sum[j]=num1[i]-'a'+10;
    }
    for(i=len2-1,j=0;i>=0;i--,j++)
    {
        if(num2[i]>='0'&&num2[i]<='9')
          n2[j]=num2[i]-'0';
        else
            n2[j]=num2[i]-'a'+10;
    }
    for(i=0;i<len;i++)
    {
        sum[i]+=n2[i];
        if(sum[i]>=20)
        {
            sum[i+1]+=sum[i]/20;
            sum[i]%=20;
        }
    }
    int l=len+2;
    while(sum[l]==0) l--;
    return l;
}
int main()
{
    int i,len,sum[MAX];
    char num1[MAX],num2[MAX];
    while(~scanf("%s %s",num1,num2))
    {
      memset(sum,0,sizeof(sum));
      len=Addition(num1,num2,sum);
      if(len<0)
        printf("0\n");
      else
      {
        for(i=len;i>=0;i--)
        {
          if(sum[i]<=9)
              printf("%d",sum[i]);
          else
              printf("%c",sum[i]-10+'a');
        }
         printf("\n");
      }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ZCMU_2024/article/details/83040935
ZOJ
今日推荐