[LeetCode/Python] 12. Integer to Roman

도니·2025년 9월 28일

Interview-Prep

목록 보기
18/29
post-thumbnail

📌 Problem

[LeetCode] 12. Integer to Roman

📌 Solution

class Solution:
    def intToRoman(self, num: int) -> str:
        if not (1 <= num <= 3999):
            raise ValueError("Input must be in 1..3999")

        vals = [
            (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 vals:
            if num == 0:
                break
            q, num = divmod(num, v)
            res.append(sym * q)
        return "".join(res)
profile
Where there's a will, there's a way

0개의 댓글