I passed the Roman Numeral Converter. If I place my answer variable as a global variable, my code does not work, it logs something like ‘M’ 90 times, and ‘I’ once, if i type a number such as 9001. If i place my answer variable inside of the function, it works fine. Why is this?
let decNum = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
let romNum = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
function convertToRoman(num) {
let answer = ''
for (let i = 0; i < decNum.length; i++){
while (decNum[i] <= num) {
answer+= romNum[i];
num-= decNum[i];
}
}
return answer;
}
convertToRoman(4);