JSFiddle - React, Tailwind, and code Playground
by Nic Fontaine
JavaScript
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
let total = 0;
s = s.split("");
const key = {
"M": 1000,
"CM": 900,
"D": 500,
"CD": 400,
"C": 100,
"XC": 90,
"L": 50,
"XL": 40,
"X": 10,
"IX": 9,
"V": 5,
"IV": 4,
"I": 1
}
for (let i = 0; i < s.length; i++) {
if (s[i+1] && (s[i] + s[i+1]) in key) {
total += key[s[i]+s[i+1]];
i++;
}
else {
total += key[s[i]];
}
}
return total;
};
console.log(romanToInt("MCMXCIV"));