Roman Numeral Converter
3 min readJul 27, 2021
JavaScript Algorithms and Data Structures Projects — freeCodeCamp
Problem Description :
Convert the given number into a roman numeral.
All roman numeral answers should be provided in upper-case.
Solution Steps :
- We first convert the given number to string and change it to an array with each character/digit of it as an element.
- Create an array to store roman symbols in order so that we can use it by it’s index.
- Let’s declare a variable to store our result and initialize it with an empty string. Declare another variable that holds a condition to check whether the given decimal number is of greater than or equal to 3digits in it(i.e. whether the number is ≥ 100)
- Now we can loop over the given string form number from least significant digit side to the most significant side as long as the condition allows us(i.e. till we reach thousand, as after thousand we will prepend only ‘M’s to the result)
- Yes, you are almost there, Just calculating number of thousands to prepend that particular number of ‘M’s to the result string and returning it is all we have.
Provided code here for your reference.
function convertToRoman(num) {
let numArray = String(+num).split('');
let romans =['','I','II','III','IV','V','VI','VII','VIII','IX','',
'X','XX','XXX','XL','L','LX','LXX','LXXX','XC','',
'C','CC','CCC','CD','D','DC','DCC','DCCC','CM'];
let resultRoman = '';
let condition = numArray.length>=3 ? 3 : numArray.length;
for(let i = 0;i<condition; i++){
let popped = +numArray.pop()+(i*10);
let str = (romans[popped]||'');
resultRoman = str+resultRoman;
}
return Array(+numArray.join('')+1).join('M')+resultRoman;
}
convertToRoman(12);//XII
convertToRoman(2938);//MMCMXXXVIII
Thank You !
I would be happy to hear your suggestions/improvements.