daily-algorithms icon indicating copy to clipboard operation
daily-algorithms copied to clipboard

Roman To Integer

Open barretlee opened this issue 7 years ago • 2 comments

本题难度:★

给定一个罗马数字(1~3999),将其转换为整数。

例如罗马数字 MCDXXXVII 对应数字为:1437。

相关资料:https://github.com/barretlee/daily-algorithms/issues/9

参考答案:https://github.com/barretlee/daily-algorithms/blob/master/answers/10.md

barretlee avatar Jul 13 '17 04:07 barretlee

罗马数字的规律还是比较容易掌握的,

function resolve(roman) {
  var map = {
    M: 1000, 
    D: 500, 
    C: 100,
    L: 50, 
    X: 10,
    V: 5, 
    I: 1
  };
  var index = 0, integer = 0;
  while(roman[index++]) {
    integer += map[roman[index - 1]] * (
      map[roman[index - 1]] < (map[roman[index]] || 0) ? -1 : 1
    );
  }
  return integer;
}

console.assert(resolve('MCDXXXVII') === 1437, 1437);

barretlee avatar Jul 13 '17 05:07 barretlee

var romanToInt = function(s) {
    const romanMap = {
      I: 1,
      V: 5,
      X: 10,
      L: 50,
      C: 100,
      D: 500,
      M: 1000
    };
    const tempArr = s.split("");
    let result = 0;
    tempArr.forEach((item, index) => {
      const next = romanMap[tempArr[index+1]];
      const current = romanMap[tempArr[index]];
      const pre = index>=1 ? romanMap[tempArr[index-1]] : false;
      if (next>current && pre != current) {
        result -= current;
      } else {
        result += current;
      }
    });
    return result;
};

stayhpjinng avatar Jul 13 '17 08:07 stayhpjinng