您的位置:首页 > 其它

ACM程序设计 书中题目H(20进制的加法)

2017-03-19 17:22 375 查看
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
这道题我想了很多,但实现起来都非常困难,而且容易出错。最后借鉴了同学的成品。
思路是这样的:
先用整形字符串数组把每一位相加的值存起来,比如两个各位分别是11 12 整形数组就存23。存好每一位后,用本位除以20就是要进几,本位就%20;即a[i+1]=a[i]/20;a[i]=a[i]%20;循环起来就好了,最后转回字符输出。
代码如下:
#include<bits/stdc++.h>
using namespace std;
int main()
{
char a[105],b[105],c;
int i,j,k;
while(cin>>a>>b)
{
int num[205]={0};
j=strlen(a)-1;
k=strlen(b)-1; //读取两个字符串的长度,便于后面从个位开始运算
for(i=0;j>=0||k>=0;i++) //当两个数都累加完成时,结束循环
{
if(j>=0) //将字符串每一位的值累加到整形数组中,若累加完成,便结束
{
if(a[j]>='0'&&a[j]<='9')
num[i]+=(a[j]-'0');
else
num[i]+=(a[j]-'a'+10);
j--;
}
if(k>=0) //同上
{
if(b[k]>='0'&&b[k]<='9')
num[i]+=(b[k]-'0');
else
num[i]+=(b[k]-'a'+10);
k--;
}
num[i+1]+=num[i]/20;
num[i]=num[i]%20; //满20进一,这就是为什么要使用整形数组来存储结果的原因
}
if(num[i]==0)
i-=1; //这是一个易错点,第一次失败的原因也在此,以下有对这里的说明(注1)
for(;i>=0;i--)
{
if(num[i]>=0&&num[i]<=9)
c=num[i]+'0';
else
c=num[i]-10+'a';
cout<<c; //转化回字符型并输出
}
cout<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: