力扣题-12.22
[力扣刷题攻略] Re:从零开始的力扣刷题生活
力扣题1:12. 整数转罗马数字
解题思想:首先构建字符和数值的映射(考虑特殊情况),然后从大到小进行遍历即可
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;
}
};