SDE & MLE Prep

12. Integer to Roman

Problem

Convert an integer from 1 to 3999 to a Roman numeral, using the subtractive forms IV, IX, XL, XC, CD and CM where they apply.

Example: 58 → "LVIII"; 3749 → "MMMDCCXLIX"

Greedy over the 13 symbol values in descending order, including the subtractive pairs (900 CM, 400 CD, 90 XC, …).

Complexity: O(1) (bounded output).

class Solution:
    def intToRoman(self, num: int) -> str:
        table = [(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")]
        res = []
        for v, sym in table:
            k, num = divmod(num, v)
            res.append(sym * k)
        return "".join(res)