Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Roman To Integer #10

Open
barretlee opened this issue Jul 13, 2017 · 2 comments
Open

Roman To Integer #10

barretlee opened this issue Jul 13, 2017 · 2 comments

Comments

@barretlee
Copy link
Owner

barretlee commented Jul 13, 2017

本题难度:★

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

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

相关资料:#9

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

@barretlee
Copy link
Owner Author

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

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);

@stayhpjinng
Copy link

stayhpjinng commented Jul 13, 2017

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;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants