Javascript Number Integer Convert Roman Numeral

Description

Javascript Number Integer Convert Roman Numeral

function convertToRoman(num) {
  var romanNumeralDefinitions = [[1000, "M"], [500, "D"], [100, "C"], [50, "L"], [10, "X"], [5, "V"], [1, "I"]];
  var romanNumeralResult = [];
  var modResult;//from w  w w.  j  ava 2 s .  c o  m
  var divResult;
    
  for (var i = 0; i < romanNumeralDefinitions.length; i++) {
    modResult = num % romanNumeralDefinitions[i][0];
    if (modResult === 0) {
      romanNumeralResult.push(romanNumeralDefinitions[i][1]);
      break;
    } else {
      divResult = (num - modResult) / romanNumeralDefinitions[i][0];
      for (var j = 0; j < divResult; j++) {
        romanNumeralResult.push(romanNumeralDefinitions[i][1]);
        
      }
    }
  }
  return romanNumeralResult;
}

console.log(convertToRoman(2));
console.log(convertToRoman(3));
console.log(convertToRoman(4));
console.log(convertToRoman(5));



PreviousNext

Related