Roman Numeral Converter - Answers not accepted

Roman Numeral Converter - Answers not accepted
0.0 0

#1

Hey guys, for some reason my solution to this challenge is not accepted by FCC.
Can someone tell me what I’m missing?
The code of course works.

// DECLARING THE ROMAN NUMERIC DICTIONARY OBJECT
var romans = {
  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"
};

//Roman Numeral String Builder
var romanNumeral = "";

function convertToRoman(num) {
  //ITERATE THROUGH ALL THE KEYS
  for (i=0; i<Object.keys(romans).length; i++) {
    // If the number is in the dictionary, add the roman numeral and return.
    if (num == Object.keys(romans)[i]) { romanNumeral += romans[Object.keys(romans)[i]]; return romanNumeral; }
    // If it's not in the dictionary, look up the closest number by seeing if NUM is smaller
    else if (num <= Object.keys(romans)[i]) {
      // Once larger number found, step back. 
      // Add the equivalent roman numeral to the string
      romanNumeral += romans[Object.keys(romans)[i-1]];
      // Subtract it from NUM
      num -= Object.keys(romans)[i-1];
      // Re-run the function with the sum after subtraction
      return convertToRoman(num);
    }
  }
}
// To Demonstrate
convertToRoman(1006);

#2

You define romanNumeral above the function. So if the the function gets run for a second time it will just add to the result of the first function call.

You could change this:

if (num == Object.keys(romans)[i]) { 
  romanNumeral += romans[Object.keys(romans)[i]]; 
  return romanNumeral;
}

to something like this:

if (num == Object.keys(romans)[i]) { 
  romanNumeral += romans[Object.keys(romans)[i]]; 
  var x = romanNumeral;
  romanNumeral = "";
  return x; 
}

Though it will still not pass convertToRoman(3999), which doesn’t work right now either.


#3

Thanks! I knew I missed something.
Added MMMCM as well. Works now :slight_smile: