Hi, I’ve been stuck on this challenge for hours. So eventually restarted it and found out a solution using a for-loop, my first attempt didn’t manage to pass all the tests, here’s what I had:
function convertToRoman(num) {
var romanSym = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
var romanVal = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
var converted = "";
var i = 0;
convertNum(num);
function convertNum (n) {
while (n > 0) {
//console.log(n / romanVal[i]);
if (n / romanVal[i] >= 1) {
converted += romanSym[i];
n = n - romanVal[i];
console.log(n + " - " + converted);
convertNum(n);
}
i++;
}
}
//console.log(converted);
return converted;
}
//convertToRoman(36);
console.log("29 roman: " + convertToRoman(29));
I tried logging the output and found n reached 0 and went back up to 5 during converting 29 to roman.
19 - X
9 - XX
0 - XXIX
5 - XXIXIV
1 - XXIXIVIV
0 - XXIXIVIVI
29 roman: XXIXIVIVI
Should of terminated at XXIX
45 to roman:
5 - XL
0 - XLV
4 - XLVI
3 - XLVII
2 - XLVIII
1 - XLVIIII
0 - XLVIIIII
45 roman: XLVIIIII
Should of terminated at XLV
So I am not sure what went wrong…can anyone point out the mistakes to me? Thanks!