Roman Numerals

!Mac OS X-10.15.7!ruby-2.7.1p83

Task

Write a method that takes Arabic numerals and returns Roman numerals https://qiita.com/daddygongon/items/2d0a73a51ddab2d9da1b

answer

code

Note: 4 is IV, 9 is IX, 99 is XCIX

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

   if n >= 4000 then
   puts"Make it less than 4000! !!"
   else
   i = 0
#+BEGIN_SRC lisp
class Integer
  def to_roman()
    rkey = ['I','V','X','L','C','D','M']
    troman = ""
    roman = self.digits.each_with_index.map do |num,i|
      one_c = rkey[i*2]
      five_c = rkey[i*2+1]
      ten_c = rkey[(i+1)*2]

      case num
      when 1..3 then troman += one_c*num
      when 4 then troman += one_c+five_c
      when 5 then troman += five_c
      when 6..8 then troman += five_c + one_c * (num-5)
      when 9 then troman += one_c + ten_c
      end

    end
    return troman
  end
end

[1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 14, 15, 19, 38, 42, 49, 51, 97, 99, 100, 200, \
439, 483, 499, 732, 961, 999, 1999].each do |i|
  puts "#{i}: #{i.to_roman}"
end

result

   1: I
   2: II
   4: IV
   5: V
   6: VI
   9: IX
  10: X
  11: XI
  14: XIV
  15: XV
  19: XIX
  38: XXXVIII
  42: XLII
  49: XLIX
  51: LI
  97: XCVII
  99: XCIX
 439: CDXXXIX
 483: CDLXXXIII
 499: CDXCIX
 732: DCCXXXII
 961: CMLXI
 999: CMXCIX
1999: MCMXCIX

Recommended Posts

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)