欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

整数转罗马数字(贪心, C++和python)

程序员文章站 2023-03-25 09:18:27
12. 整数转罗马数字题目链接这道题力扣题解上面给出了很多解法,贪心是目前逻辑最简单且效率高的。先把最大值1000替换,替换完成再替换900,以此类推……C++:class Solution {public: string intToRoman(int num) { vector key = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; vector

12. 整数转罗马数字

题目链接
整数转罗马数字(贪心, C++和python)
整数转罗马数字(贪心, C++和python)
这道题力扣题解上面给出了很多解法,贪心是目前逻辑最简单且效率高的。
先把最大值1000替换,替换完成再替换900,以此类推……
C++:

class Solution {
public:
    string intToRoman(int num) {
        vector<int> key = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        vector<string> value = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        string ans = "";
        for(int i = 0; i < 13; i++)
        {
            while(num >= key[i])
            {
                ans += value[i];
                num-=key[i];
            }
        }
        return ans;
    }
};

整数转罗马数字(贪心, C++和python)

python:

class Solution:
    def intToRoman(self, num: int) -> str:
        key = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
        value = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
        ans = ""
        for i in range(0, 13):
            while num >= key[i]:
                ans += value[i]
                num -= key[i]
        return ans

整数转罗马数字(贪心, C++和python)
如果对你有帮助的话,请点个赞哦!

本文地址:https://blog.csdn.net/qq_41946404/article/details/109952822

相关标签: leetcode