Skip to content

Instantly share code, notes, and snippets.

@ppworks
Created April 26, 2012 03:49
Show Gist options
  • Save ppworks/2495648 to your computer and use it in GitHub Desktop.
Save ppworks/2495648 to your computer and use it in GitHub Desktop.
Convert a Number into Roman Numerals.
module Roman
CHAR = "IVXLCDM"
def self.to_num n
return "" if n <= 0 || 5000 <= n
str = sprintf("%04d", n).reverse!
res = ''
4.times do|i|
res = "#{roman_char(str[i], i*2)}#{res}"
end
res
end
def self.roman_char n, i
n = n.to_i
arr = CHAR[i,3]
case n
when 1..3
arr[0] * n
when 5
arr[1]
when 4
arr[0] + arr[1]
when 6..8
arr[1] + (arr[0] * (n-5)).to_s
when 9
arr[0] + arr[2].to_s
else
''
end
end
end
def test num, expect
if Roman.to_num(num) === expect
print "."
else
puts "#{num} does't convert to #{expect}"
end
end
test 1, 'I'
test 2, 'II'
test 3, 'III'
test 4, 'IV'
test 5, 'V'
test 6, 'VI'
test 7, 'VII'
test 8, 'VIII'
test 9, 'IX'
test 10, 'X'
test 24, 'XXIV'
test 50, 'L'
test 100, 'C'
test 500, 'D'
test 1000, 'M'
test 2751, 'MMDCCLI'
test 1999, 'MCMXCIX'
test -1, ''
test 0, ''
test 5001, ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment