标签:replace continue man cas fun tin turn ace OLE
使用eval,特别处理6个case
var romanToInt = function (s) {
const map = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
var fns = '0' + s.replace('CM', '+900').
replace('CD', '+400').
replace('XL': '+40').
replace('XC', '+90').
replace('IV', '+4').
replace('IX', '+9').
replace(/[C-X]/g, function (c) {
return "+" + map[c]
})
return eval(fns)
};
console.log(intToRoman("MCMXCIV"))
不使用eval
var romanToInt = function (s) {
const map = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
const specialMap = {
CM: 900,
CD: 400,
XL: 40,
XC: 90,
IV: 4,
IX: 9
}
var sum = 0
for (var i = 0; i < s.length; i++) {
var c = s[i];
var more = c + s[i + 1];
if (specialMap[more]) {
sum += specialMap[more];
i += 1;
continue
} else {
sum += map[c]
}
}
return sum
};
方法3, 我们可以观察一下 下一个字符代码的数值是否比当前的大,大则减去。
var romanToInt = function (s) {
const map = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
var sum = 0
for (var i = 0; i < s.length; i++) {
var c = s[i];
var curr = map[c]
var after = s[i + 1];
if (map[after] > curr) {
sum -= curr
} else {
sum += curr
}
}
return sum
};
标签:replace continue man cas fun tin turn ace OLE
原文地址:https://www.cnblogs.com/rubylouvre/p/12040415.html