Here’s my not-so-pretty code for this challenge. It works, but I don’t understand why I had to put index += 1 just in that one “special” case.
First I thought that my code should work without adding that index += 1 in the second else if. However, I got red ticks for 798, 891, 97 and by looking at their outputs, I noticed that it’s as if the while loop is not functioning for adding the last digits (“I”-s). Example: I would get XCV instead of XCVII.
I also noticed it happens only if the second to last arabic number digit is 9, so I increased the index in that case only, but I do not understand why this happens. If somebody could help, would be much appreciated!
function convertToRoman(num) {
var result = [];
var Arabic = [1000,500,100,50,10,5,1];
var Roman = ["M", "D", "C", "L", "X", "V", "I"];
var index = 0;
for (var i = 0; i < Roman.length; i++) {
if (num < 1000 && num >= 900) {
result.push("CM");
num -= 900;
continue;
} else if (num < 500 && num >= 400){
result.push("CD");
num -= 400;
continue;
} else if (num < 100 && num >= 90) {
result.push("XC");
num -= 90;
index += 1;
continue;
} else if (num < 50 && num >= 40) {
result.push("XL");
num -= 40;
continue;
} else if (num < 10 && num >= 9 ) {
result.push("IX");
num -= 9;
continue;
} else if (num < 5 && num >= 4) {
result.push("IV");
num -= 4;
continue;
}
while (num >= Arabic[index]) {
result.push(Roman[index]);
num -= Arabic[index];
}
index += 1;
}
return result.join("");
}