整数转罗马数字
思路1:模拟
- 注意不能用map来储存key、value,map默认从小到大,而我们需要从大到小匹配,当然,也可以自定义匹配规则使map从大到小排序。
const pair<int, string> roman2num[] = {
{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:
string intToRoman(int num) {
string roman;
for (auto & rom : romam2num) {
while (num >= rom.first) {
num -= rom.first;
res += rom.second;
}
if (num == 0) break;
}
return res;
}
};