本文主要是介绍力扣题:数字与字符串间转换-12.22,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
力扣题-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 -= keytemp += valueif num == 0:breakreturn 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;}
};
这篇关于力扣题:数字与字符串间转换-12.22的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!