Skip to content

Instantly share code, notes, and snippets.

@RainMonster
Created October 30, 2013 18:16
Show Gist options
  • Save RainMonster/7237372 to your computer and use it in GitHub Desktop.
Save RainMonster/7237372 to your computer and use it in GitHub Desktop.
Roman Numerals with driver code, both Iterative and Recursive.
NUM_HASH = {
1000 => "M",
500 => "D",
100 => "C",
50 => "L",
10 => "X",
9 => "IX",
5 => "V",
4 => "IV",
1 => "I"
}
def arabic_to_roman(num, string = '')
unless num == 0
NUM_HASH.each do |arabic, roman|
if num >= arabic
until num < arabic
string += roman
num -= arabic
### for solving recursively:
arabic_to_roman(num, string)
### for solving iteratively:
# if num == 0
# return string
# end
end
end
end
end
string
end
puts arabic_to_roman(2002)
puts arabic_to_roman(1000)
puts arabic_to_roman(734)
puts arabic_to_roman(205)
puts arabic_to_roman(51)
puts arabic_to_roman(9)
puts arabic_to_roman(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment