Skip to main content
30. November 2021

Roman Numeral Converter

Arabische in römische Ziffern umwandeln.

function convertToRoman(num) {
  if (typeof num == "undefined" || typeof num != "number" || num > 3999) {
    return false;
  }

  let romans = "";
  const symbols = [
    [1000, "M"],
    [500, "D"],
    [100, "C"],
    [50, "L"],
    [10, "X"],
    [5, "V"],
    [1, "I"],
  ];

  // 1000
  let aa = num;
  let n1000 = parseInt(aa / 1000);

  for (let i = 0; i < n1000; i++) {
    romans += symbols[0][1];
  }

  let subTotal1 = aa;
  let subTotal5;
  let n1;
  let n5;

  for (let i = 1; i < symbols.length; i++) {

    if (i % 2) {
      // 5, 50, 500
      subTotal5 = (subTotal1 % symbols[i - 1][0]) - symbols[i][0];
      n5 = subTotal5 >= 0 ? 1 : 0;

      for (let j = 0; j < n5; j++) {
        romans += symbols[i][1];
      }
    } else {
      // 1, 10, 100
      subTotal1 = subTotal5 < 0 ? subTotal1 % symbols[i - 1][0] : subTotal5 % symbols[i - 1][0];
      n1 = parseInt(subTotal1 / symbols[i][0]);

      if (n1 > 3 && n5 >= 1) {
        romans =
          romans.substring(0, romans.length - 1) +
          symbols[i][1] +
          symbols[i - 2][1];
      } else if (n1 > 3) {
        romans += symbols[i][1] + symbols[i - 1][1];
      } else {
        for (let k = 0; k < n1; k++) {
          romans += symbols[i][1];
        }
      }
    }
  }

  return romans;
}

console.log(convertToRoman(3999));

convertToRoman(2) should return the string II.

convertToRoman(3) should return the string III.

convertToRoman(4) should return the string IV.

convertToRoman(5) should return the string V.

convertToRoman(9) should return the string IX.

convertToRoman(12) should return the string XII.

convertToRoman(16) should return the string XVI.

convertToRoman(29) should return the string XXIX.

convertToRoman(44) should return the string XLIV.

convertToRoman(45) should return the string XLV.

convertToRoman(68) should return the string LXVIII

convertToRoman(83) should return the string LXXXIII

convertToRoman(97) should return the string XCVII

convertToRoman(99) should return the string XCIX

convertToRoman(400) should return the string CD

convertToRoman(500) should return the string D

convertToRoman(501) should return the string DI

convertToRoman(649) should return the string DCXLIX

convertToRoman(798) should return the string DCCXCVIII

convertToRoman(891) should return the string DCCCXCI

convertToRoman(1000) should return the string M

convertToRoman(1004) should return the string MIV

convertToRoman(1006) should return the string MVI

convertToRoman(1023) should return the string MXXIII

convertToRoman(2014) should return the string MMXIV

convertToRoman(3999) should return the string MMMCMXCIX

freeCodeCamp