Last active
September 12, 2019 23:23
-
-
Save haikelfazzani/62b708c7fc244fd06341d78aa702c7db to your computer and use it in GitHub Desktop.
Convert a number into a Roman Numeral
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 integerToRoman(num) { | |
let o = { | |
M: 1000, CM: 900, D: 500, CD: 400, | |
C: 100, XC: 90, L: 50, XL: 40, | |
X: 10, IX: 9, V: 5, IV: 4, I: 1 | |
} | |
let result = '' | |
Object.keys(o).map(i => { | |
while (num >= o[i]) { | |
result += i; | |
num -= o[i]; | |
} | |
}) | |
return result | |
} | |
/* | |
3 -> Output: "III" | |
4 -> Output: "IV" | |
9 -> Output: "IX" | |
*/ | |
function romanToInteger (s) { | |
let r = 0; | |
let i = 0; | |
let o = { M: 1000, D: 500, C: 100, L: 50, X: 10, V: 5, I: 1 }; | |
while (++i < s.length) { | |
c = o[s[i]] | |
p = o[s[i - 1]] | |
r += c <= p ? c : c-p*2 | |
} | |
return o[s[0]] + r | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment