您的位置:首页 > 其它

PAT乙级练习题B1044. 火星数字

2016-07-10 23:17 417 查看

题目描述

火星人是以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,169),即只有两位13进制数,我没注意,弄复杂了。

注意cin和getline之间需要加一个空的getchar(),这样第一个getline才会正确的执行。

注意如果是13的整数末位tret不显示。

代码

#include<iostream>
#include<string>
#include<map>
#include<vector>
#include<cmath>
using namespace std;

int main()
{
int N;
map<string, int>mars2dig;
vector<string> mars1 = { "tret" ,"jan", "feb", "mar", "apr", "may", "jun", "jly", "aug", "sep", "oct", "nov", "dec" };
vector<string> mars2 = { "tam", "hel", "maa", "huh", "tou", "kes", "hei", "elo", "syy", "lok", "mer", "jou" };
for (int i = 0; i < 13; ++i)
{
mars2dig[mars1[i]] = i;
}
for (int i = 0; i < 12; ++i)
{
mars2dig[mars2[i]] = (i+1)*13;
}
cin >> N;
getchar();
for (int i = 0; i < N; ++i)
{
string str;
getline(cin, str);
if (str[0] >= '0'&&str[0] <= '9')
{
int earth=0;
for (int j = str.size() - 1,p = 0,dig; j >= 0; --j)
{
dig = str[j] - '0';
earth += dig*pow(10, p++);
}
vector<int> mars_out;
do
{
mars_out.push_back(earth % 13);
earth /= 13;
} while (earth);
string out;
for (int j = 0; j < mars_out.size(); ++j)
{
if (j == 0)
{
if (mars_out.size() > 1 && mars_out[j] == 0)
{
continue;
}
out = mars1[mars_out[j]];
}
else
{
if (!out.empty())
{
out = mars2[mars_out[j] - 1] + " " + out;
}
else
{
out = mars2[mars_out[j] - 1];
}
}
}
cout << out << endl;
}
else
{
int earth = 0;
for (int j = str.size()-3,dig,p=0; j >=0 ; j -= 4)
{
string mars_dig = str.substr(j, 3);
dig = mars2dig[mars_dig];
if (dig > 12&& j != str.size() - 3)
{
dig /= 13;
}
earth += dig*pow(13, p++);
}
cout << earth << endl;
}
}
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: