用於將羅馬數字轉換為十進位制數字的 JavaScript 演算法


我們需要編寫一個函式,該函式取一個羅馬數字字串並返回其十進位制(基數 10)等價物。因此,讓我們為該函式編寫程式碼 −

示例

const romanToInt = (s) => {
   const legend = "IVXLCDM";
   const l=[1,5,10,50,100,500,1000];
   let sum=0;
   while(s){
      if(!!s[1] && legend.indexOf(s[0]) < legend.indexOf(s[1])){
         sum += (l[legend.indexOf(s[1])] - l[legend.indexOf(s[0])]);
         s = s.substring(2, s.length);
      } else {
         sum += l[legend.indexOf(s[0])];
         s = s.substring(1, s.length);
      }
   }
   return sum;
};
console.log(romanToInt('CLXXVIII'));
console.log(romanToInt('LXXXIX'));
console.log(romanToInt('LV'));
console.log(romanToInt('MDLV'));

輸出

控制檯中的輸出將為 −

178
89
55
1555

更新日期:21-Aug-2020

391 次瀏覽

啟動你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.