Skip to content

Instantly share code, notes, and snippets.

@absk1317
Created June 8, 2021 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save absk1317/365863b7463b798a81cd01f42b723837 to your computer and use it in GitHub Desktop.
Save absk1317/365863b7463b798a81cd01f42b723837 to your computer and use it in GitHub Desktop.
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