How to use a Lookup Object In Javascript
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.
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
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
Contact Us