Created
August 23, 2017 06:17
-
-
Save wisetara/026e28cbb4b9208492551f84546fdd9f to your computer and use it in GitHub Desktop.
Convert Arabic Roman Numbers with Ruby
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
class Fixnum | |
# Unique + special roman numerals | |
ROMANS = { 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' }.freeze | |
def to_roman | |
ROMANS[self] || divide_and_conquer_roman(self) | |
end | |
private | |
def divide_and_conquer_roman(number) | |
ROMANS.reduce('') do | numeral, (arabic, roman) | | |
quotient, number = number.divmod(arabic) | |
numeral << roman * quotient | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment