My solution for: Roman Numeral Converter

Feedback appreciated!

http://codepen.io/salasy/full/BLyoZa/

I never thought of parsing individual characters from the string input, and listing all possible Roman numeral values per position. And awesome converter page :thumbsup:! I was thinking you could change this so the output is shown as you type (and restrict input to numbers only).

My solution
function convertToRoman(num) {
  function values(roman, decimal) {
    return {
      roman: roman,
      decimal: decimal
    };
  }
  var table = [
    values('M', 1000),
    values('CM', 900),
    values('D', 500),
    values('CD', 400),
    values('C', 100),
    values('XC', 90),
    values('L', 50),
    values('XL', 40),
    values('X', 10),
    values('IX', 9),
    values('V', 5),
    values('IV', 4),
    values('I', 1)
  ];
  
  var n = num;
  var roman = '';
  var i = 0;
  while (n > 0) {
    if (n >= table[i].decimal) {
      roman += table[i].roman;
      n -= table[i].decimal;
    }
    else {
      i++;
    }
  }
  return roman;
}
1 Like

I agree with kevcomedia, very nice implementation!

Thank you both for your comments.
Yes, I’ll try to find time and restrict input to numbers only.

This is exactly what I had in my mind but was not sure how to go about the adding of repetitious characters without making my code full of annoying if statements. Thanks for sharing. My submitted solution used the full table in a object like salsy’s.

How much extra code do you think it will be to remove the 4, 9, 40, 90 etc. from your solution?

My Solution
    var romanNumerals = {
      1: "I",
      2: "II",
      3: "III",
      4: "IV",
      5: "V",
      6: "VI",
      7: "VII",
      8: "VIII",
      9: "IX",
      10: "X",
      20: "XX",
      30: "XXX",
      40: "XL",
      50: "L",
      60: "LX",
      70: "LXX",
      80: "LXXX",
      90: "XC",
      100: "C",
      200: "CC",
      300: "CCC",
      400: "CD",
      500: "D",
      600: "DC",
      700: "DCC",
      800: "DCCC",
      900: "CM",
      1000: "M",
      2000: "MM",
      3000: "MMM",
    };

    function convertToRoman(num) {
      var numArray = num.toString().split("").map(function(value) {
        return parseInt(value); 
      });
      
      for (var i = 0; i < numArray.length; i++) {
         var itemNum = i + 1;
           
         if (numArray[i] !== 0 && itemNum !== numArray.length) {
            numArray[i] *= Math.pow(10, numArray.length - itemNum) ;  
         }
        
         if (numArray[i] !== 0) {
           numArray[i] = romanNumerals[numArray[i]];  
         } else {
           numArray[i] = '';
         }
         
      }
      
      numArray = numArray.join("");
      
      return numArray;
    }