火星人是以 13 进制计数的:
- 地球人的 0 被火星人称为 tret。
- 地球人数字 1 到 12 的火星文分别为:jan, feb, mar, apr, may, jun, jly, aug, sep, oct, nov, dec。
- 火星人将进位以后的 12 个高位数字分别称为:tam, hel, maa, huh, tou, kes, hei, elo, syy, lok, mer, jou。
例如地球人的数字 29
翻译成火星文就是 hel mar
;而火星文 elo nov
对应地球数字 115
。为了方便交流,请你编写程序实现地球和火星数字之间的互译。
输入格式:
输入第一行给出一个正整数 N(<100),随后 N 行,每行给出一个 [0, 169) 区间内的数字 —— 或者是地球文,或者是火星文。
输出格式:
对应输入的每一行,在一行中输出翻译后的另一种语言的数字。
输入样例:
4
29
5
elo nov
tam
输出样例:
hel mar
may
115
13
思路: 用字符串接受输入,然后,输入分为两类,一类是纯数字的字符数组没有空格;一类是纯字母的字符串,有空格;以空格划分火星数字。这道题的重要思想就是把一个问题分解成好多个子问题,分别解决这些问题。以函数抽象某个功能,减少主函数代码的复杂性。写两个函数来就是把那个字符串转化成相应的数字,通过数字来匹配那个常量字符串数组。
数字转字符时,先减去‘0’,然后乘以对应的权重(进制数的次方),转化为十三进制数,将十三进制数储存在一个数组里,分别对应不同的字符串常量数组进行输出。
注意:这里有个比较坑的点是如果一个数字%13==0;那么在储存十三进制数字的那个数组中会存一个0(对应tret),但是题目已经给出来了那个高位数字,所以输出tret是多余的;解决办法是再加一个if,分类讨论
字符转数字时,分为三类,无空格(ini,alt),有空格(ini+alt),前者直接匹配输出,后者把空格换为'/0',然后匹配输出;
#include <stdio.h>
#include <string.h>
#include <math.h>
#define N 13
#define M 100
char* init[N] = {"tret","jan", "feb", "mar", "apr", "may", "jun","jly", "aug",
"sep", "oct", "nov", "dec"};
char* alt[N] = {"","tam", "hel", "maa", "huh", "tou", "kes",
"hei", "elo", "syy", "lok", "mer", "jou"};
void TranToStr(char a[]);
void TranToNum(char a[]);
void TranSingleNum(int* a, int n);
int main() {
char custIn[M][8];
int i, j, n;
scanf("%d",&n);//按下enter键以后,/r/n或者/n会被发送到输入流中,而gets函数会读取/n;
// char t = getchar();//换行:10,回车:13;
// printf("%d",t);
getchar();
for(i = 0; i < n; i++)
{
gets(custIn[i]);
}
//printf("n =%s",custIn[0]);
for(i = 0; i < n; i++) {
if('0' <= custIn[i][0] && custIn[i][0] <= '9') {
TranToStr(custIn[i]);
}
else{
TranToNum(custIn[i]);
}
if(i != n - 1) printf("\n");
}
return 0;
}
void TranToStr(char a[]) {
int tem[2]= {0};
int t = 0, i = 0;
int len = strlen(a);
for(i = 0; i < len; i++) {
t += (a[i]-'0')*pow(10,len-1-i);
}
int index = 0;
while(t != 0) {
tem[index] = t % 13;
index++;
t /= 13;
}
if(index == 1) {
printf("%s",init[tem[0]]);
}
else if(index == 2) {
if(tem[0] == 0)
printf("%s",alt[tem[1]]);
else
printf("%s %s",alt[tem[1]],init[tem[0]]);
}
else{
printf("tret");
}
}
void TranToNum(char a[]){
int i = 0,j, blank = -1;
while(a[i] != '\0') {
if(a[i] == ' '){
blank = i;
break;
}
i++;
}
if(blank == -1) {
for(j = 0; j < N; j++) {
if(strcmp(a,init[j]) == 0)
break;
}
if(j == N){
for(j = 0; j < N; j++) {
if(strcmp(a,alt[j]) == 0)
printf("%d",13*j);
}
}
else{
printf("%d",j);
}
}
else{
char* p = &a[blank+1];
char q[8];
strcpy(q,p);
a[blank] = '\0';
// printf("%s\n",a);
// printf("%s\n",q);
int ge,shi;
for(j = 0; j < N; j++) {
if(strcmp(a,alt[j]) == 0) {//strcmp的返回值有三种,只有当返回值为零时
//才表明两个字符串完全相同,大于零时则表明str1 > str2;
shi = j;
}
if(strcmp(q,init[j]) == 0) {
ge = j;
}
}
// printf("%d %d\n",shi,ge);
printf("%d",shi*13+ge);
}
}
void TranSingleNum(int* a, int n) {
}
第一次,自己几乎完全没看题解,做完了一个题目,虽然还不是满分,但是感觉挺有成就感,自己独立的解决了这个问题,棒!
还有就是把问题分块处理的思想(分而治之),分类讨论,还有,逆向思维,以函数抽象某个功能,最后,要有耐心,完整的解决一个问题,慢就是快,注重学习的质量;
最后,附上柳神的博客: