Last active
January 2, 2016 12:59
-
-
Save fallengiants/8307213 to your computer and use it in GitHub Desktop.
Roman Numerals
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
| 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