Open In App

Javascript Program to Convert Integer to Roman Numerals

Given an Integer number, the task is to convert the Integer to a Roman Number in JavaScript. Roman numerals are a numeral system that originated in ancient Rome and remained the usual way of writing numbers throughout Europe well into the Late Middle Ages.

Using a Lookup Object

One common approach is to use a lookup object that maps integers to their corresponding Roman numeral values and then iterates over this object to construct the Roman numeral.

Explanation:

function integerToRoman(num) {
    const romanValues = {
        M: 1000,
        CM: 900,
        D: 500,
        CD: 400,
        C: 100,
        XC: 90,
        L: 50,
        XL: 40,
        X: 10,
        IX: 9,
        V: 5,
        IV: 4,
        I: 1
    };
    let roman = '';
    for (let key in romanValues) {
        while (num >= romanValues[key]) {
            roman += key;
            num -= romanValues[key];
        }
    }
    return roman;
}

// Driver code
console.log(integerToRoman(58));
console.log(integerToRoman(1994));

Output
LVIII
MCMXCIV

Using Arrays

An alternative approach is to use arrays to store the Roman numeral symbols and their corresponding integer values, and then iterate over these arrays.

Explanation:

function integerToRoman(num) {
    const values = 
        [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
    const symbols = 
        ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
    let roman = '';
    for (let i = 0; i < values.length; i++) {
        while (num >= values[i]) {
            roman += symbols[i];
            num -= values[i];
        }
    }
    
    return roman;
}

// Driver code
console.log(integerToRoman(58));
console.log(integerToRoman(1994));

Output
LVIII
MCMXCIV
Article Tags :