Created
September 5, 2019 05:39
-
-
Save rakin92/71e817888de5250b02e197144a861e3f to your computer and use it in GitHub Desktop.
converts roman numeral to number.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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