Created
May 17, 2017 23:47
-
-
Save jkulton/3e842a11f78f3cbceacbcd06267a8693 to your computer and use it in GitHub Desktop.
Roman Numeral to int
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
def rom_to_int(input, total=0) | |
return total if input.length === 0 | |
roman_numerals = { | |
"I" => 1, | |
"V" => 5, | |
"X" => 10, | |
"L" => 50, | |
"C" => 100, | |
"D" => 500, | |
"M" => 1000 | |
}; | |
if input.length > 1 && roman_numerals[input[0]] < roman_numerals[input[1]] | |
total += roman_numerals[input.slice!(1)] - roman_numerals[input.slice!(0)] | |
else | |
total += roman_numerals[input.slice!(0)] | |
end | |
rom_to_int(input, total) | |
end | |
puts "MCMXCIX => #{rom_to_int('MCMXCIX')}" | |
puts "LXXIV => #{rom_to_int('LXXIV')}" | |
puts "DCCCXC => #{rom_to_int('DCCCXC')}" | |
puts "IV => #{rom_to_int('IV')}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment