Skip to content

Instantly share code, notes, and snippets.

@railsstudent
Last active February 4, 2017 11:50
Show Gist options
  • Save railsstudent/adbfb14a034c9da91a657d14ad6c0f59 to your computer and use it in GitHub Desktop.
Save railsstudent/adbfb14a034c9da91a657d14ad6c0f59 to your computer and use it in GitHub Desktop.
class RomanNumerals
literalMap = {
'I' : 1,
'V' : 5,
'X' : 10,
'L' : 50,
'C' : 100,
'D' : 500,
'M' : 1000
}
toNumberMap = [
[1000, 'M'],
[900, 'CM'],
[500, 'D'],
[400, 'CD'],
[100, 'C'],
[90, 'XC'],
[50, 'L' ],
[40, 'XL'],
[10, 'X'],
[9, 'IX'],
[5, 'V'],
[4, 'IV'],
[1, 'I'],
]
@toRoman: (number) ->
tempNumber = number
result = ''
for e in toNumberMap
while e[0] <= tempNumber
tempNumber -= e[0]
result = result + e[1]
result
@fromRoman: (roman) ->
numeric = 0
for i in [0...roman.length - 1]
firstVal = literalMap[roman[i]]
secondVal = literalMap[roman[i+1]]
if firstVal < secondVal then numeric += -firstVal else numeric += firstVal
numeric += literalMap[roman[roman.length - 1]]
numeric
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment