Skip to content

Instantly share code, notes, and snippets.

@mariapacana
Created May 9, 2013 18:58
Show Gist options
  • Save mariapacana/5549678 to your computer and use it in GitHub Desktop.
Save mariapacana/5549678 to your computer and use it in GitHub Desktop.
Converts integers to Roman numerals.
def numerals_subtraction(int)
values = %w(M D C L X V I)
roman_num = ""
values = {"M" => 1000, "D" => 500, "C" => 100, "L" => 50, "X" => 10, "V" => 5, "I" => 1}
values.keys.each do |i|
if (int % values[i]) then
roman_num << i*(int / values[i]) # Equal to the quotient
remainder = (int % values[i]).to_s
msd = remainder[0].to_i
print "i = #{i}, int = #{int}, values[i] = #{values[i]}, int/values = #{int/values[i]} , msd = #{msd}\n"
if msd == 9
if (remainder.length == 3)
roman_num << "CM"
int = int - 900
elsif (remainder.length == 2)
roman_num << "XC"
int = int - 90
else
roman_num << "IX"
int = int - 9
end
elsif msd == 4
if (remainder.length == 3)
roman_num << "CD"
int = int - 400
elsif (remainder.length == 2)
roman_num << "XL"
int = int - 40
else
roman_num << "IV"
int = int - 4
end
else
int = int % values[i] # Equal to the remainder
end
end
end
roman_num
end
puts numerals_subtraction(494)
puts numerals_subtraction(400)
puts numerals_subtraction(900)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment