Roman Numeral Converter - [SOLVED]

Roman Numeral Converter - [SOLVED]
0.0 0


im dealing with this algorithm for some time and i dont know how what to do …

function convertToRoman(num) {
  var numbers = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
  var roman = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
  var result = "";
  for(var i = 0; i < numbers.length; i++) {
    if(numbers[i] == num) {
      result += roman[i];

 return result;



Initially the issue you have is when 3 is entered as the parameter into this function and the for loop checks whether num equals a value in the number array it won’t find it. This function will only work if the number inputed exactly matches the values in the array. Therefore the only way this function could work is if you created a value in your array to match every possible number inputed into the function which is very inefficient.

Try thinking about it differently. Rather than trying to get the function to match numbers exactly, try using > or < comparisons to eliminate options.

For example, if you enter 156 then you know that the number is larger than 100 but less than 500 so it has to contain C. Then the 56 remaining is greater than 50 but less than 60 so must next contain L. Finally the remaining 6 value is VI. Therefore the conversion is CLVI.

Using this logic you can save yourself writing a value to each conversion.