输入:num = 1994
输出:"MCMXCIV"
题意:将整数转罗马数字。罗马数字I-1,V-5,X-10,L-50,C-100,D-500,M-1000,除了这些数之外,其他数就由这些数表示,如II-2,XXVII-27,LIV-54。
1、企图用哈希表来做
只能枚举了。
class Solution {
public:
string intToRoman(int num) {
string result;
unordered_map<int, string>hash = {
{1, "I"}, {5, "V"}, {10, "X"}, {50, "L"},
{100, "C"}, {500, "D"}, {1000, "M"}
};
while(num>=1000){
result += "M";
num -= 1000;
}
while(num>=900){
result += "CM";
num -= 900;
}
while(num>=500){
result += "D";
num -= 500;
}
while(num>=400){
result += "CD";
num -= 400;
}
while(num>=100){
result += "C";
num -= 100;
}
while(num>=90){
result += "XC";
num -= 90;
}
while(num>=50){
result += "L";
num -= 50;
}
while(num>=40){
result += "XL";
num -= 40;
}
while(num>=10){
result += "X";
num -= 10;
}
while(num>=9){
result += "IX";
num -= 9;
}
while(num>=5){
result += "V";
num -= 5;
}
while(num>=4){
result += "IV";
num -= 4;
}
while(num>=1){
result += "I";
num -= 1;
}
return result;
}
};
2、看看官方咋搞
官方跟我上面写的一个意思。就是大大地精简了代码量。主要学到了pair的初始化和遍历。
class Solution {
public:
string intToRoman(int num) {
pair<int, string> pair[] = {
{1000, "M"},
{900, "CM"},
{500, "D"},
{400, "CD"},
{100, "C"},
{90, "XC"},
{50, "L"},
{40, "XL"},
{10, "X"},
{9, "IX"},
{5, "V"},
{4, "IV"},
{1, "I"},
};
string result;
for(auto &[value, symbol] : pair){
while(num>=value){
num -= value;
result += symbol;
}
}
return result;
}
};