Created
June 8, 2021 17:38
-
-
Save absk1317/365863b7463b798a81cd01f42b723837 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
MAP = { | |
1 => ['I', 'V', 'X'], | |
2 => ['X', 'L', 'C'], | |
3 => ['C', 'D', 'M'], | |
4 => ['M', 'M', 'M'] | |
} | |
def to_roman(numeral) | |
roman_numeral = '' | |
i = 1 | |
loop do | |
place = numeral % 10 | |
this_place = '' | |
if i == 4 | |
this_place = MAP[i][0] * place | |
roman_numeral = this_place + roman_numeral | |
break | |
elsif place.between?(1,3) | |
this_place = MAP[i][0] * place | |
elsif place == 4 | |
this_place = MAP[i][0] + MAP[i][1] | |
elsif place.between?(5,8) | |
this_place = MAP[i][1] | |
this_place += MAP[i][0] * (place - 5) | |
elsif place == 9 | |
this_place = MAP[i][0] + MAP[i][2] | |
elsif place == 0 && i == 3 | |
i += 1 | |
end | |
roman_numeral = this_place + roman_numeral | |
i += 1 if i < 4 | |
numeral /= 10 | |
break if numeral == 0 | |
end | |
roman_numeral | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment