Skip to content

Instantly share code, notes, and snippets.

@uttamk
Created September 26, 2021 03:15
Show Gist options
  • Save uttamk/f1b25e1ff2b5de674d44a512626cf625 to your computer and use it in GitHub Desktop.
Save uttamk/f1b25e1ff2b5de674d44a512626cf625 to your computer and use it in GitHub Desktop.
const romanToInt = function (s) {
let total = 0;
for (let i = 0; i < s.length;) {
let currentVal = valueMap[s[i]];
if (i === s.length - 1) {
total += currentVal;
break;
}
let nextVal = valueMap[s[i + 1]];
if (currentVal < nextVal) {
total += nextVal - currentVal;
i += 2;
} else {
total += currentVal;
i += 1;
}
}
return total
};
const valueMap = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment