Skip to content

Instantly share code, notes, and snippets.

@jkulton
Created May 17, 2017 23:47
Show Gist options
  • Save jkulton/3e842a11f78f3cbceacbcd06267a8693 to your computer and use it in GitHub Desktop.
Save jkulton/3e842a11f78f3cbceacbcd06267a8693 to your computer and use it in GitHub Desktop.
Roman Numeral to int
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