Last active
October 29, 2018 05:32
-
-
Save nishanbajracharya/5736a9424e59dceffc31d94cefcfb7cb to your computer and use it in GitHub Desktop.
Convert roman to integer
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
const ROMAN = { | |
I: 1, | |
V: 5, | |
X: 10, | |
L: 50, | |
C: 100, | |
D: 500, | |
M: 1000 | |
} | |
const toInt = c => ROMAN[c] || 0; | |
const convertRoman = string => { | |
const str = string.toUpperCase(); | |
let res = 0; | |
if (str.length === 1) return toInt(str); | |
for (let i = 0; i < str.length; i++) { | |
const curr = toInt(str[i]); | |
const next = toInt(str[i + 1]); | |
if (curr >= next) { // eg XI | |
res += curr; // Add and iterate | |
} else { // eg IX | |
res += next - curr; // Subtract the first from second | |
i++; // Second character is accounted for. | |
} | |
} | |
return res; | |
} | |
const cases = ['I', 'M', 'II', 'III', 'IV', 'IX', 'X', 'XI', 'XC']; | |
console.log(cases.map(c => convertRoman(c))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment