JS罗马数字转整数

  let obj = {
    "I": 1,
    "V": 5,
    "X": 10,
    "L": 50,
    "C": 100,
    "D": 500,
    "M": 1000
  }

  function fn(v) {
    let res = 0;
    for (var i = 0; i < v.length; i++) {
      let front = v[i];
      let back = v[i + 1];
      if (obj[back] > obj[front]) {
        res -= obj[front]
      } else {
        res += obj[front]
      }
    }
    return res;
  }

  console.log(fn("MCXCIV"));

发表评论

电子邮件地址不会被公开。 必填项已用*标注