DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 12. Integer to Roman

/**
 * @param {number} num
 * @return {string}
 */
var intToRoman = function(num) {

    let integerToRomanMap = {
        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"
    };


    /* In JavaScript, when you compare a number (num) with a string (value), JavaScript implicitly converts  the string to a number before making the comparison.*/

    let result = "";
    for (let value of Object.keys(integerToRomanMap).reverse()) {
        while (num >= value) {
            result += integerToRomanMap[value];
            num -= value;
        }
    }

    return result;


};



Enter fullscreen mode Exit fullscreen mode

Top comments (0)