AFFILIATE LINKS
Great resource I use to learn algorithms.
40% off Tech Interview Pro: http://techinterviewpro.com/terriblewhiteboard
20% off CoderPro: http://coderpro.com/terriblewhiteboard
Here is the full implementation.
/**
* @param {string} s
* @return {number}
*/
let romanToInt = function(s) {
let romanToInt = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
}
let total = 0;
for (let i = 0; i < s.length; i++) {
let currentInt = romanToInt[s.charAt(i)];
let nextInt = romanToInt[s.charAt(i + 1)];
if (nextInt) {
if (currentInt >= nextInt) {
total += currentInt;
} else {
total += (nextInt - currentInt);
i++;
}
} else {
total += currentInt;
}
}
return total;
};