Skip to content

Instantly share code, notes, and snippets.

@fallengiants
Last active January 2, 2016 12:59
Show Gist options
  • Select an option

  • Save fallengiants/8307213 to your computer and use it in GitHub Desktop.

Select an option

Save fallengiants/8307213 to your computer and use it in GitHub Desktop.
Roman Numerals
class Integer
Roman = 'IVXLCDM'
def to_roman
raise "Number too large" if self > 3999
num = self
num_size = Math.log10(num).to_i
# for each num_size.downto(0),
# get which character to display for that level.
num_size.downto(0).map do |pow|
mid = (pow * 2) + 1
current = (num / (10 ** pow))
num = num % (10 ** pow)
# do this the long way then condense
retval = ''
mods = current % 5
retval << Roman[mid-1] if mods == 4
retval << Roman[mid + (current == 9 ? 1 : 0)] if current >= 4
retval << (Roman[mid-1] * mods) if mods < 4
retval
end.join
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment