Stuck on Roman Numeral

Hello everyone! I’ve found myself in a pickle with this particular project. Below is my rather lengthy code:

function convertToRoman(num) {
  const romanNums = [
    "M",
    "CM",
    "D",
    "CD",
    "C",
    "XC",
    "L",
    "XL",
    "X",
    "IX",
    "V",
    "IV",
    "I",
  ];
  const decNumbers = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
  let romanNumConvert = "";

  while (num - 1000 >= 0) {
    romanNumConvert += "M";
    num -= 1000;
  }
  while (num - 900 >= 0) {
    romanNumConvert += "CM";
    num -= 900;
  }
  while (num - 500 >= 0) {
    romanNumConvert += "D";
    num -= 500;
  }
  while (num - 400 >= 0) {
    romanNumConvert += "CD";
    num -= 400;
  }
  while (num - 100 >= 0) {
    romanNumConvert += "C";
    num -= 100;
  }
  while (num - 90 >= 0) {
    romanNumConvert += "XC";
    num -= 90;
  }
  while (num - 50 >= 0) {
    romanNumConvert += "L";
    num -= 50;
  }
  while (num - 40 >= 0) {
    romanNumConvert += "XL";
    num -= 40;
  }
  while (num - 10 >= 0) {
    romanNumConvert += "X";
    num -= 10;
  }
  while (num - 9 >= 0) {
    romanNumConvert += "IX";
    num -= 9;
  }
  while (num - 5 >= 0) {
    romanNumConvert += "V";
    num -= 5;
  }
  while (num - 4 >= 0) {
    romanNumConvert += "IV";
    num -= 4;
  }
  while (num - 1 >= 0) {
    romanNumConvert += "I";
    num -= 1;
  }
  return romanNumConvert;
}
convertToRoman(36);

It passes some of the tests but fails on others like 97,99,649, etc. My question is, how can I refactor this code so that I’m not using all of these loops and where do I go from here? I’ve thought about hard coding a switch statement but I don’t really want to do that as it seems as tedious and slow as my while loop conglomerate I have going on already.

Any and all help is greatly appreciated!

Alright, I figured out my problem. I had some incorrect values in my while loops.

But since you’re already here, does anyone have any suggestions on how to refactor this code? It works and passes the tests but it is…in a word…hideous :smiley:

Well, you have a lot of repeated code, and you have two arrays with the Roman and Arab numbers, can you figure out how to reduce the repeteated code using those two arrays?

This wouldn’t make it more efficient, but would reduce the repeated code and so the risk for typos

1 Like

Thank you for pointing me in the right direction…I think I’m on to something with looping over the arrays and using one loop instead of the multiple loops I have.

I really appreciate it!

1 Like