Roman Character Converter - I don't understand a part of my own code

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! :slight_smile:

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("");
}

That’s because of the continue statement. The for loop will go around exactly 7 times, but the index variable won’t get increased on those times when one of your conditions is met. Which means, sometimes index will go only up to 5, and you’ll never be checking for how many 1s fit in the remaining number. Lots of numbers will trigger that: 901, 42, and so on. Basically, everything that triggers a “special case” at least once, but then should have to subtract 1 by 1 at the end.

The simplest fix that I can see is that the index variable is redundant. Just use i inside the while loop.
(alternatively, increase the index every time before you call continue, but that’s more typing :wink: )

2 Likes

Thanks a lot @foresterr. Very simple and clear explanation!
:slight_smile: