用于将整数转换为罗马数字的JavaScript算法

假设,我们需要编写一个函数say intToRoman(),顾名思义,该函数返回罗马数字,该数字等于传入的数字作为参数。

让我们为该函数编写代码-

示例

const intToRoman = (num) => {
   let result = "";
   while(num){
      if(num>=1000){
         result += "M";
         num -= 1000;
      }else if(num>=500){
         if(num>=900){
            result += "CM";
            num -= 900;
         }else{
            result += "D";
            num -= 500;
         }
         }else if(num>=100){
            if(num>=400){
               result += "CD";
               num -= 400;
            }else{
               result += "C";
               num -= 100;
            }
         }else if(num>=50){
            if(num>=90){
               result += "XC";
               num -= 90;
            }else{
               result += "L";
               num -= 50;
            }
         }else if(num>=10){
            if(num>=40){
               result += "XL";
               num -= 40;
            }else{
               result += "X";
               num -= 10;
            }
         }else if(num>=5){
            if(num>=9){
               result += "IX";
               num -= 9;
           }else{
               result += "V";
               num -= 5;
            }
         }else{
            if(num>=4){
               result += "IV";
               num -= 4;
         }else{
            result += "I";
            num -= 1;
         }
      }
   }
   return result;
};
console.log(intToRoman(178));
console.log(intToRoman(89));
console.log(intToRoman(55));
console.log(intToRoman(1555));

输出结果

控制台中此代码的输出为-

CLXXVIII
LXXXIX
LV
MDLV