We'er going to kick things off by creating 2 variables. One will store our numbers, and the other will store the corresponding roman numeral, and both will go from highest to lowest.
This will allow us to associate a number with its counterpart. Note: Remember to put each number and roman numeral as a string within the overall array.
let numbers = ['1000', '900', '500', '400', '100', '90', '50', '40', '10', '9', '5', '4', '1']
let romans = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
let result = ''
Now that we have this dict ready, we can loop through the number and find out if the number given is greater than the current number.
If it is, we will add the corresponding roman numeral to a result variable, then we will subtract the given number by the current number.
We will continue to do this loop until we are 0 and then we return the result string.
let numbers = ['1000', '900', '500', '400', '100', '90', '50', '40', '10', '9', '5', '4', '1']
let romans = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
let result = ''
//loop through numbers
for (let i = 0; i < numbers.length; i++){
//set variable to current number
let current = numbers[i]
//while the number equal the current number or is
bigger then it
while (num >= current) {
//add the corresponding numeral to the result
string
result += romans[i]
//subtract the num by the current current in the
numbers array
num-=current
}
}
//return the result
return result
};
Top comments (0)