# Help in roman numeral converter

Help in roman numeral converter
0

#1

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!

#2

When I try to run your code, Chrome locks up, so I’d guess that it ends up looping and not satisfying an exit conditional somehow.

You can copy your function, paste it into the Chrome debugger console and hit Enter, then run `convertToRoman(29)` in the console and single-step thru the debugger: tedious, but it can shed some light on the issue.

It looks as though the value of i exceeds the length of your `romanSym` array after a point.

#3

Managed to finish the challenge in the end without the recursion…seems like my logic is wrong somewhere…
Finished code:

``````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;

while (i < romanVal.length) {
while (num >= romanVal[i]) {
converted += romanSym[i];
num = num - romanVal[i];
console.log(num + " - " + converted);
}
i++;
}

return converted;
}

convertToRoman(36);
``````

PS: If someone were to read it later on and knows where went wrong holla at me ! Would love to know where it went wrong. Many thanks in advance!

#4

You need to create another array for the roman numbers, loop over both and assign numbers[index] = romanValue[index]