Open In App

Javascript Program to Convert Integer to Roman Numerals

Last Updated : 05 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • integerToRoman Function: This function takes an integer as an argument and returns its Roman numeral representation.
  • lookup Object: Maps Roman numeral symbols to their integer values.
  • Looping Over the lookup Object: For each key in the lookup object, the function repeatedly subtracts the corresponding value from num and adds the key to the roman string until num is less than the value.
JavaScript
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:

  • integerToRoman Function: Similar to the first approach, but uses parallel arrays values and symbols instead of a lookup object.
  • Looping Over the Arrays: The function iterates over the values array, and for each value, it subtracts it from num and adds the corresponding symbol from the symbols array to the roman string.
JavaScript
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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads