Converting integers to roman numerals

前端 未结 29 2535
走了就别回头了
走了就别回头了 2020-12-02 09:16

I\'m trying to write a function that converts numbers to roman numerals. This is my code so far; however, it only works with numbers that are less than 400. Is there a quick

29条回答
  •  不知归路
    2020-12-02 09:40

    A neat, quick and straightforward solution

    function convertToRoman(num) {
    
      //Roman numerals to have <= 3 consecutive characters, the distances between deciaml values conform to this
      var decimalValue = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ];
      var romanNumeral = [ 'M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I' ];
      var num_cp = num; // copy the function parameter into num_cp
      var result = '';
    
      for (var i=0; i < decimalValue.length; i++){ //itarate through array of decimal values
          //iterate more to find values not explicitly provided in the decimalValue array
        while (decimalValue[i] <= num_cp){
          result += romanNumeral[i];
          num_cp -= decimalValue[i];
        }
      }
      return result;
    }
    
    convertToRoman(477);
    

提交回复
热议问题