Tell us what’s happening:
some test results are not working such as 2,3,12 etc
Your code so far
function convertToRoman(num) {
var roman="";
var romanN=["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"];
var p=[1000,900,500,400,100,90,50,40,10,9,5,4,1];
for(var i=0;i<p.length;i++)
{
if(num>=p[i])
{
roman=roman + romanN[i];
num=num-p[i];
}
}
return roman;
}
convertToRoman(2);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/roman-numeral-converter/
That is a really elegant solution. I think you just need one small change. Try stepping through it with the number 2 to see what happens… The if statement will be false while i is less that 12. so when the for loop is entered at i = 12 the if statement will be true 2 >= p[12] (aka 1) thus roman will become “” + “I”, num will become 2-1 and the if statement will finish and the next step in the for loop will increment i to 13 which will end the for loop and return. Is your if statement doing what you want so?
In his other post he shows that the function does pass some tests, and his function is certainly working properly, but as you pointed out it does not handle those multiples of each digit such as 1, 10, 100 (“I”, “X”, “C”).
I wouldn’t call it elegant, it’s mostly hand-written comparisons and doesn’t quite work. Though it is simple and I do like the solution to subtract the value from p when there is a match, I wonder if that trick only works with how the function is built, and I wonder what needs to change to make it work.
Don’t want to spoil it on the OP so
.
.
.
.
.
.
.
.
.
Replace if with a while?