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!