!Mac OS X-10.15.7 !ruby-2.7.1p83
課題
アラビア数字(arabic numerals)を受け取って,ローマ数字(roman numerals)を返すmethodを書きなさいhttps://qiita.com/daddygongon/items/2d0a73a51ddab2d9da1b
解答
コード
注意点:4はIV、9はIX、99はXCIX
def to_roman()
roman_key = ['I', 'V', 'X', 'L', 'C', 'D', 'M']
result = ""
if n >= 4000 then
puts"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
結果
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
- source ~/grad_members_20f/members/wjswnsrud12/roman.org