Integer to Roman numeral

Medium TimeO(1) SpaceO(1)

Every number from 1 to 3999 has one standard Roman numeral: the one written with the fewest symbols, which is why 900 is "CM" and not "DCCCC". Given num, return that numeral. No symbol appears more than three times in a row, and the six subtractive pairs CM, CD, XC, XL, IX and IV are used wherever they fit.

Examples

Example 1

Input
num = 1994
Output
"MCMXCIV"
1000 + 900 + 90 + 4, one symbol group each: M, CM, XC, IV.

Example 2

Input
num = 3000
Output
"MMM"
1000 + 1000 + 1000, the same symbol three times.

The Code

function intToRoman(num) {
  const values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
  const symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];
  let out = "";
  for (let i = 0; i < values.length; i++) {
    while (num >= values[i]) {
      out += symbols[i];
      num -= values[i];
    }
  }
  return out;
}
intToRoman(1994);
Done

The first 17 calls, of 23. This one does not fit on a page.

Step through intToRoman(1994) call by call