Created
June 20, 2018 00:54
-
-
Save basekays/6fd05565b44b7b24f7ad71b471a38577 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| //input string | |
| //output number | |
| // I can be placed before V (5) and X (10) to make 4 and 9. | |
| // X can be placed before L (50) and C (100) to make 40 and 90. | |
| // C can be placed before D (500) and M (1000) to make 400 and 900. | |
| var romanToInt = function(string) { | |
| var reference = { | |
| 'I': 1, | |
| 'V': 5, | |
| 'X': 10, | |
| 'L': 50, | |
| 'C': 100, | |
| 'D': 500, | |
| 'M': 1000, | |
| }; | |
| var result = 0; | |
| for (var i = 0; i < string.length; i++) { | |
| if (string[i] == 'I' && (string[i+1] == 'V' || string[i+1] == 'X')) { | |
| result = result + (reference[string[i+1]] - reference[string[i]]); | |
| i++; | |
| } else if (string[i] == 'X' && (string[i+1] == 'L' || string[i+1] == 'C')) { | |
| result = result + (reference[string[i+1]] - reference[string[i]]); | |
| i++; | |
| } else if (string[i] == 'C' && (string[i+1] == 'D' || string[i+1] == 'M')) { | |
| result = result + (reference[string[i+1]] - reference[string[i]]); | |
| i++; | |
| } else { | |
| result = result + reference[string[i]]; | |
| } | |
| } | |
| return result; | |
| }; | |
| romanToInt('LVIII'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment