How to use Arrays In Javascript

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


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.

Table of Content

  • Using a Lookup Object
  • Using Arrays

Similar Reads

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....

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....

Contact Us