Peeush Agarwal > Engineer. Learner. Builder.

I am a Machine Learning Engineer passionate about creating practical AI solutions using Machine Learning, NLP, Computer Vision, and Azure technologies. This space is where I document my projects, experiments, and insights as I grow in the world of data science.

View on GitHub

Intuition

To convert an integer to a Roman numeral, repeatedly subtract the largest possible Roman value from the number and append its symbol to the result. Special cases like 4, 9, 40, 90, 400, and 900 use subtractive notation (e.g., IV, IX, XL, XC, CD, CM).

Approach

Complexity

Code

class Solution:
    def intToRoman(self, num: int) -> str:
        mapper = {
            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",
        }

        ans = ""
        for x, s in mapper.items():
            s_times = num // x
            ans += s * s_times
            num = num % x

            if num <= 0:
                break

        return ans

Back to Problem Statement