Problem 12: Integer to Roman
This commit is contained in:
parent
ca927211b5
commit
65a5392783
2 changed files with 56 additions and 0 deletions
32
problems/12-integer-to-roman/main.rb
Normal file
32
problems/12-integer-to-roman/main.rb
Normal file
|
@ -0,0 +1,32 @@
|
|||
# @param {Integer} num
|
||||
# @return {String}
|
||||
def int_to_roman(num)
|
||||
res = ''
|
||||
|
||||
if num >= 1000
|
||||
res += 'M' * (num / 1000)
|
||||
num %= 1000
|
||||
end
|
||||
|
||||
if num >= 100
|
||||
res += to_roman(num / 100, 'C', 'D', 'M')
|
||||
num %= 100
|
||||
end
|
||||
|
||||
if num >= 10
|
||||
res += to_roman(num / 10, 'X', 'L', 'C')
|
||||
num %= 10
|
||||
end
|
||||
|
||||
res + to_roman(num, 'I', 'V', 'X')
|
||||
end
|
||||
|
||||
def to_roman(num, one, five, ten)
|
||||
return one * num if num <= 3
|
||||
|
||||
return one + five if num == 4
|
||||
|
||||
return five + one * (num - 5) if num <= 8
|
||||
|
||||
one + ten
|
||||
end
|
24
problems/12-integer-to-roman/test.rb
Normal file
24
problems/12-integer-to-roman/test.rb
Normal file
|
@ -0,0 +1,24 @@
|
|||
require_relative 'main'
|
||||
require 'test/unit'
|
||||
|
||||
class TestIntegerToRoman < Test::Unit::TestCase
|
||||
def test_simple_integer
|
||||
assert_equal('III', int_to_roman(3))
|
||||
end
|
||||
|
||||
def test_complex_integer
|
||||
assert_equal('LVIII', int_to_roman(58))
|
||||
end
|
||||
|
||||
def test_substaction
|
||||
assert_equal('MCMXCIV', int_to_roman(1994))
|
||||
end
|
||||
|
||||
def test_smallest_number
|
||||
assert_equal('I', int_to_roman(1))
|
||||
end
|
||||
|
||||
def test_largest_number
|
||||
assert_equal('MMMCMXCIX', int_to_roman(3999))
|
||||
end
|
||||
end
|
Loading…
Reference in a new issue