题目摘要:It is a well-known fact that behindevery good comet is a UFO. These UFOs often come to collect loyal supportersfrom here on Earth. Unfortunately, they only have room to pick up one group offollowers on each trip. They do, however, let the groups know ahead of timewhich will be picked up for each comet by a clever scheme: they pick a name forthe comet which, along with the name of the group, can be used to determine ifit is a particular group's turn to go (who do you think names the comets?). Thedetails of the matching scheme are given below; your job is to write a programwhich takes the names of a group and a comet and then determines whether thegroup should go with the UFO behind that comet.
Both the name of the group and the name of thecomet are converted into a number in the following manner: the final number isjust the product of all the letters in the name, where "A" is 1 and"Z" is 26. For instance, the group "USACO" would be 21 * 19* 1 * 3 * 15 = 17955. If the group's number mod 47 is the same as the comet'snumber mod 47, then you need to tell the group to get ready! (Remember that"a mod b" is the remainder left over after dividing a by b; 34 mod 10is 4.)
Write a program which reads in the name ofthe comet and the name of the group and figures out whether according to theabove scheme the names are a match, printing "GO" if they match and"STAY" if not. The names of the groups and the comets will be astring of capital letters with no spaces or punctuation, up to 6 characterslong.
题目大意:第一行输入彗星名,第二行输入组织名,将字母转换成数字,A对应1,B对应2……Z对应26,然后将对应行转换后的数字相乘,将得到的两个数对47取余,如果取余结果相同则输出GO,否则输出STAY。
输入输出样例:
Input | Output |
COMETQ HVNGAT | GO |
ABSTAR USACO | STAY |
解题思路:用两个字符数组储存彗星名和组织名,然后用强制类型转换将两串字符改成数字并储存在两个整形数组里,将两个整形数组所有元素分别相乘,比较两个结果对47取余的结果是否相等。
代码:
#include<iostream>
using namespace std;
int main()
{
inta,b;
charA1[7],B1[7];
intA2[7],B2[7];
longT1=1,T2=1;
intnn=0,mm=0;
cin>>A1;
cin>>B1;
for(int i=0;A1[i]!='\0';i++)
{
nn++;
A2[i]=(int)A1[i]-64;
}
for(int j=0;B1[j]!='\0';j++)
{
mm++;
B2[j]=(int)B1[j]-64;
}
for(int k=0;k<nn;k++)
T1=T1*A2[k];
for(int l=0;l<mm;l++)
T2=T2*B2[l];
a=T1%47;
b=T2%47;
if(a==b)
cout<<"GO"<<endl;
else
cout<<"STAY"<<endl;
return0;
}
解题感想:理解了题意后很快有了思路,但是在将字母转换成数字这里卡住了,本来用switch语句做的,这样就有26个case,特别麻烦,后来郭朋华一句话点醒了我,借助ASC||码值用强制类型转换就可以了,这样代码显得短多了一目了然。相信以后再遇到类似情况就有了解决方法。