HJ5.进制转换
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <cmath>
const int DIG = 16;
const std::unordered_map<char, int> DICT = {
{'0', 0},
{'1', 1},
{'2', 2},
{'3', 3},
{'4', 4},
{'5', 5},
{'6', 6},
{'7', 7},
{'8', 8},
{'9', 9},
{'A', 10},
{'B', 11},
{'C', 12},
{'D', 13},
{'E', 14},
{'F', 15},
};
int trans(std::string s) {
int ret = 0;
if (s.length() > 2) {
int slen = s.length();
for (int i = 0; i < slen - 2; ++i) {
ret += DICT.at(s[slen - 1 - i]) * pow(DIG, i);
}
}
return ret;
}
int main() {
std::string input;
while (getline(std::cin, input)) {
std::cout << trans(input) << std::endl;
}
return 0;
}
解题思路:
难点1:进制转换的原理;
难点2:输入输出;
难点3:unordered_map与cmath的熟悉程度;
知识点:
知识点1:c++使用getline读取一整行,循环读取整行如下所示
std::string input;
while (getline(std::cin, input)) {
std::cout << input << std::endl;
}
知识点2:unordered_map可直接使用”{}“初始化
const std::unordered_map<char, int> DICT = {
{'0', 0},
{'1', 1},
{'2', 2}
};
知识点3:map在被const修饰的情况下,使用at取值
int val = DICT.at('0');