解题思想:首先构建字符和数值的映射(考虑特殊情况),然后从大到小进行遍历即可
class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
dic = [(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")]
temp = ''
for key,value in dic:
while num>=key:
num -= key
temp += value
if num == 0:
break
return temp
class Solution {
public:
string intToRoman(int num) {
std::vector<std::pair<int, std::string>> dic = {
{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"}
};
std::string result = "";
for (const auto& pair : dic) {
while (num >= pair.first) {
num -= pair.first;
result += pair.second;
}
if (num == 0) {
break;
}
}
return result;
}
};