2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

roman numerals

Last updated at Posted at 2020-12-21

!Mac OS X-10.15.7 !ruby-2.7.1p83

課題

アラビア数字(arabic numerals)を受け取って,ローマ数字(roman numerals)を返すmethodを作成する.

コード

def to_roman(num)
  roman=['I','V','X','L','C','D','M']
  num_s=ARGV[0]
  num=num_s.to_i
  x=num/1000  #1000の位
  num=num%1000
  y=num/100   #100の位
  num=num%100
  z=num/10    #10の位
  num=num%10
  w=num       #1の位
  case x
  when 1,2,3 then
    result=roman[6]*x
  end

  case y
  when 1,2,3 then
    result+=roman[4]*y
  when 4 then
    result+=roman[4]+roman[5]
  when 5 then
    result+=roman[5]
  when 6,7,8 then
    result+=roman[5]+roman[4]*(y-5)
  when 9 then
    result+=roman[4]+roman[6]
  end

  case z
  when 1,2,3 then
    result+=roman[2]*z
  when 4 then
    result+=roman[2]+roman[3]
  when 5 then
    result+=roman[3]
  when 6,7,8 then
    result+=roman[3]+roman[2]*(z-5)
  when 9 then
    result+=roman[2]+roman[4]
  end

  case w
  when 1,2,3 then
    result+=roman[0]*x
  when 4 then
    result+=roman[0]+roman[1]
  when 5 then
    result+=roman[1]
  when 6,7,8 then
    result+=roman[1]+roman[0]*(x-5)
  when 9 then
    result+=roman[0]+roman[2]
  end
  return result
end

puts "#{to_roman(ARGV[0])}"

結果

>ruby roman_numeral.rb 1960

MCMLX

  • source ~/grad_members_20f/members/Kenny0704/roman.org
2
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?