PAT 1110 C++版【updating…】
1.题意
给出[0,169)范围内的数值【on earth,10进制】,或者是字符【火星上,13进制】。请把这些值相互转换。
2.分析
- 简单的数值转换题,但是因为这个题目讲得不清楚,导致试错了很久。
For the next higher digit, Mars people name the 12 numbers as “tam, hel, maa, huh, tou, kes, hei, elo, syy, lok, mer, jou”, respectively.
刚开始,一直没有理解这段话的意思,其实理解了也没用。我一直以为这个tam, hel, maa, huh, tou, kes, hei, elo, syy, lok, mer, jou是用于高位,但是没想到,对于13,39,130这样的值的时候,就需要单独输出这个结果,而且后面的tret字符串是不用添加上的。
- 虽然这个很好写。但问题是写的有多快。给你两个小时,写出这道题,与你不会写这道题是一样的结果。
3.代码
#include<cstdio>
#include<cstring>
#include<stack>
#include<string>
#include<iostream>
using namespace std;
char first [13][5]={"tret","jan", "feb", "mar", "apr", "may", "jun", "jly", "aug", "sep", "oct", "nov", "dec"};
char secon [13][5]={"","tam", "hel", "maa", "huh", "tou", "kes", "hei", "elo", "syy", "lok", "mer", "jou"};
stack<string> sta;
//operate number
int opeNum(char str[] ){
int index = 0;
int length = strlen(str);
int res=0;
while(index < length){
res = res* 10 + str[index] - '0';
index ++;
}
return res;
}
void numToChar(int num){
int bit_1;
int bit_2;
bit_1 = num % 13; //使用13 进制
int count = 0;
if(bit_1!=0) {
sta.push(first[bit_1]);
count++;
}
if(num == 0){
sta.push("tret");
}
if(num/13 != 0) {
num /= 13;
sta.push(secon[num]);
count++;
}
while(!sta.empty()){
cout << sta.top();
sta.pop();
if(--count > 0){
cout << " ";
}
}
printf("\n");
}
int opeStr(char str[]){
int index = 0;
int length = strlen(str);
int res = 0;
char part1[10];
char part2[10];
if(length == 7){
while(str[index]!=' '){
part1[index] = str[index];
index++;
}
part1[index]='\0';
index ++;
while(str[index]!=' ' && str[index]!='\0'){
part2[index-4] = str[index];
index++;
}
part2[index-4]='\0';
}
else{
while(str[index]!=' ' && str[index]!='\0'){
part1[index] = str[index];
index++;
}
part1[index]='\0';
}
if(length == 7){//如果是两位数 【13进制】
for(int j = 0;j< 13;j++){
if(strcmp(part1,secon[j]) == 0){
res = (j)* 13;
break;
}
}
for(int j = 0;j< 13;j++){
if(strcmp(part2,first[j]) == 0){
res = res + j;
break;
}
}
}
else{//如果是一位数
for(int j = 0;j< 13;j++){
if(strcmp(part1,first[j]) == 0){
res = res + j;
break;
}
if(strcmp(part1,secon[j]) == 0){
res = j * 13;
break;
}
}
}
cout << res << endl;
}
int main(){
//printf("%s",secon[1]);
int N;
scanf("%d",&N);
getchar();//吃掉后面的那个回车
int i ;
char str[101][10];
for(i = 0;i< N;i++){
cin.getline(str[i],10);
}
int num;
for(i = 0;i< N ;i++){
if(str[i][0] >='0' && str[i][0] <='9'){//如果处理的是数字
num = opeNum(str[i]);
numToChar(num);
}else{
opeStr(str[i]);
}
}
}
- 执行结果
4.测试用例
4
29
5
elo nov
tam
4
hel mar
may
115
13
3
13
39
maa
10
0
1
2
jou dec
maa
tret
jan
feb
168
15
5.坑点
-
pat编译器已经不再支持使用gets()函数了。如果提交包含gets()函数的代码,会报编译错误。
所以对于包含空格的字符串,使用getline()函数。 - 注意空格的输出,否则会得到一个格式错误。
- 测试点2的数据 是用于测试
0 <=> tret相互转化。