PAT A1100 Mars Numbers [字符串处理+硬核模拟]

题目描述

链接
火星人是以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”。为了方便交流,请你编写程序实现地球和火星数字之间的互译

分析

  • 写两个函数进行转换
  • 传入的值是string转int后的结果stoi(s),因为数字最大不超过168,所以最多只会输出两位火星文,如果t / 13不等于0,说明有高位,所以输出b[t/13];如果输出了高位(t/13不等于0)并且t % 13不等于0,说明有高位且有低位,所以此时输出空格;如果t % 13不等于0,说明有低位,此时输出a[t % 13];注意,还有个数字0没有考虑,因为数字0取余13等于0,但是要特别输出tret,所以在func1的最后一句判断中加一句t == 0,并将a[0]位赋值成tret即可解决0的问题
  • 注意!!!t == 0的情况
  • t1和t2一开始都赋值0,s1和s2用来分离火星文单词,因为火星文字符串只可能一个单词或者两个单词,而且一个单词不会超过4,所以先将一个单词的赋值给s1,即s1 = s.substr(0, 3);如果len > 4,就将剩下的一个单词赋值给s2,即s2 = s.substr(4, 3);然后下标j从1到12遍历a和b两个数组,如果a数组中有和s1或者s2相等的,说明低位等于j,则将j赋值给t2;如果b数组中有和s1相等的(b数组不会和s2相等,因为如果有两个单词,s2只可能是低位),说明高位有值,将j赋值给t1,最后输出t1 * 13 + t2即可

代码

#include<bits/stdc++.h>
using namespace std;

string dict_s1[] = {"tret", "jan", "feb", "mar", "apr", "may", "jun", "jly", "aug", "sep", "oct", "nov", "dec"};
string dict_s2[] = {"tret", "tam", "hel", "maa", "huh", "tou", "kes", "hei", "elo", "syy", "lok", "mer", "jou"};

void convert_to_string(string s){
    int t = stoi(s);
    if (t / 13) cout << dict_s2[t / 13];
    if ((t / 13) && (t % 13)) cout << " ";
    if (t % 13 || t == 0) cout << dict_s1[t % 13];
}

void convert_to_num(string s){
    int t1 = 0, t2 = 0;
    int len = s.length();
    string s1 = s.substr(0, 3), s2;
    if (len > 4) s2 = s.substr(4, 3);
    for (int j = 1; j <= 12; j++) {
        if (s1 == dict_s1[j] || s2 == dict_s1[j]) t2 = j;
        if (s1 == dict_s2[j]) t1 = j;
    }
    cout << t1 * 13 + t2;
}

int main(){
    int n;
    string s;
    cin>>n;
    getchar();
    while(n--){
        getline(cin, s);
        if(s[0]>='0' && s[0]<='9'){
            convert_to_string(s);
        }else{
            convert_to_num(s);
        }
        cout<<endl;
    }

}

原文地址:https://www.cnblogs.com/doragd/p/11464936.html