Problem 12: Integer to Roman

This commit is contained in:
Ivan R. 2022-12-16 22:58:22 +05:00
parent ca927211b5
commit 65a5392783
No known key found for this signature in database
GPG key ID: 56C7BAAE859B302C
2 changed files with 56 additions and 0 deletions

View 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

View 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