← switch

12. Integer to Roman

medium

Hash Table · Math · String

read the problem on leetcode →

first solved 15 Aug 2024 · 2 accepted submissions

python
class Solution:
    def intToRoman(self, num: int) -> str:
        values = [
            (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")
        ]

        result = []

        for value, symbol in values:
            count, num = divmod(num, value)
            result.append(symbol * count)

        return "".join(result)
python
class Solution:
    def intToRoman(self, num: int) -> str:
        roman_dict = {1: "I",5: "V",4: "IV",10: "X",   9: "IX",50: "L",   40: "XL",100: "C",  90: "XC",500: "D",  400: "CD",1000: "M", 900: "CM"}
        out = ""
        for n in [1000,900,500,400,100,90,50,40,10,9,5,4,1]:
            while num >= n:
                out += roman_dict[n]
                num -= n
        return out