Skip to content

Instantly share code, notes, and snippets.

@rakin92
Created September 5, 2019 05:39
Show Gist options
  • Save rakin92/71e817888de5250b02e197144a861e3f to your computer and use it in GitHub Desktop.
Save rakin92/71e817888de5250b02e197144a861e3f to your computer and use it in GitHub Desktop.
converts roman numeral to number.
function fromRoman(str) {
let result = 0;
// the result is now a number, not a string
const decimal = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
const roman = ["M", "CM","D","CD","C", "XC", "L", "XL", "X","IX","V","IV","I"];
for (let i = 0;i<=decimal.length;i++) {
while (str.indexOf(roman[i]) === 0){
result += decimal[i];
str = str.replace(roman[i],'');
}
}
return result;
}
fromRoman("LXXXVII"); // returns 87
fromRoman("XLIII"); // returns 43
fromRoman("XXII"); // returns 22
fromRoman("DCCVII"); // returns 707
fromRoman("LXIX"); // returns 69
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment