// 注意位置是在class 的外部
// unordered_map的内部顺序可能和初始化的时候不一样
const pair<int, string> hmap[] = {
{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"}
};
class Solution {
public:
//对于pair对的学习
string intToRoman(int num) {
string ans="";
//pair对的循环:
for (const auto &[value, symbol] : hmap) {
while(num>=value){
num-=value;
ans+=symbol;
}
if(num==0)break;
}
return ans;
}
};
//1.use unordered_map
// 注意位置是在class 的外部
const unordered_map<int, string> hmap = {
{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"}
};
const vector<int> pos={1000,900,500,400,100,90,50,40,10,9,5,4,1};
class Solution {
public:
string intToRoman(int num) {
string ans="";
for (int i=0;i<13;i++) {
int value=pos[i];
while(num>=value){
num-=value;
ans+=hmap.at(value);//根据key获得value的方法 不能使用hmap[value],因为hmap是const,如果取消const,则可以使用hmap[value]
}
if(num==0)break;
}
return ans;
}
};