[RUBY] roman numerals

!ruby-2.7.0p0

Task

https://qiita.com/daddygongon/items/2d0a73a51ddab2d9da1b

problem

Write a method that takes arabic numerals and returns roman numerals

answer

code


class Integer
  def to_roman()
    roman_key = ['I', 'V', 'X', 'L', 'C', 'D', 'M']

    num_s = self.to_s
    result = ""
    (0..num_s.length-1).each do |i|
      n = num_s[i].to_i
      next if n == 0
      j = num_s.length-1 - i
      one_c = roman_key[j*2]
      five_c = roman_key[j*2+1]
      ten_c = roman_key[j*2+2]
      case n
      when 1..3 then result += one_c*n
      when 4 then result += one_c + five_c
      when 5 then result += five_c
      when 6..8 then result += five_c + one_c*(n-5)
      when 9 then result += one_c + ten_c
      end
    end
    return result
  end
end

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 19, 20, 38, 40, 42, 49, 50, 51, 60, 90, 97, 99, 100, 200, 400, 439, 483, 499, 500, 600, 732, 900, 961, 999, 1999, 2000, 3000].each do |i|
  puts "#{i}: #{i.to_roman}"
end

result

$ ruby roman_numerals.rb
1: I
2: II
3: III
4: IV
5: V
6: VI
7: VII
8: VIII
9: IX
10: X
11: XI
12: XII
13: XIII
14: XIV
15: XV
19: XIX
20: XX
38: XXXVIII
40: XL
42: XLII
49: XLIX
50: L
51: LI
60: LX
90: XC
97: XCVII
99: XCIX
100: C
200: CC
400: CD
439: CDXXXIX
483: CDLXXXIII
499: CDXCIX
500: D
600: DC
732: DCCXXXII
900: CM
961: CMLXI
999: CMXCIX
1999: MCMXCIX
2000: MM
3000: MMM

Recommended Posts

roman numerals
roman numerals
roman numerals
roman numerals
Roman Numerals
roman numerals
roman numerals
EX1: roman numerals
Let's solve the roman numerals
Find Roman numerals in Ruby
Convert numbers to Roman numerals in Ruby
roman numerals (I tried to simplify it with hash)