力扣题:数字与字符串间转换-12.22

2023-12-22 06:51:33

力扣题-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;
    }
};

文章来源:https://blog.csdn.net/yumeng3866/article/details/135032089
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。