daily-algorithms
daily-algorithms copied to clipboard
Roman To Integer
本题难度:★
给定一个罗马数字(1~3999),将其转换为整数。
例如罗马数字 MCDXXXVII
对应数字为:1437。
相关资料:https://github.com/barretlee/daily-algorithms/issues/9
参考答案:https://github.com/barretlee/daily-algorithms/blob/master/answers/10.md
罗马数字的规律还是比较容易掌握的,
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);
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;
};