《ACM程序设计》书中题目 H-08 火星ACM

来源:互联网 发布:武汉大学法学院 知乎 编辑:程序博客网 时间:2024/06/11 22:21

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:

1234567890abcdefghij99999jjjjj9999900001

Sample Output:
bdfi02467jiiiij00000

 这道题的基本题意为求两个不超过100位的数之和,与平常不同的是这些数采取的20进制,难点就在于10进制与20进制的转换。

源代码如下:

#include<bits/stdc++.h>using namespace std;int main(){      string a,b,e;    int i,j,k;    while(cin>>a>>b)   {   int m[103]={0};       j=a.size()-1;   k=b.size()-1;       for(i=0;j>=0||k>=0;--j,--k,++i)       { if(j<0&&k>=0){j=0;a[0]='0';}         if(j>=0&&k<0){k=0;b[0]='0';}          if(a[j]>='0'&&a[j]<='9')    m[i]+=(a[j]-'0');            else             m[i]+=(a[j]-'a'+10);           if(b[k]>='0'&&b[k]<='9')    m[i]+=(b[k]-'0');            else             m[i]+=(b[k]-'a'+10);                 m[i+1]=m[i]/20; m[i]=m[i]%20;    }    if(m[i]==0) --i;for(;i>=0;--i){if(m[i]<=9)  cout<<m[i];                       else cout<<char(m[i]-10+'a');  }              cout<<endl;   }}
  其中有许多细节需要注意,因为输入的数据不只一组,所以数组重置要在循环内;输入的两个字符串不一定一样长,还需要考虑
两字符串长度不一样长的情况;还有到最后一位相加后还要判断它是否进了位,如果没有的话计数器需要减1。

0 0
原创粉丝点击