LoginSignup
5
0

More than 3 years have passed since last update.

roman numerals

Last updated at Posted at 2020-12-09

お題

アラビア数字(arabic numerals)を受け取って,ローマ数字(roman numerals)を返すmethodを書きなさい.

ローマ数字で使われる数字

アラビア数字とローマ数字と対応付けは表の通りである.表からわかるようにローマ数字は1~3999まで表すことができる.

arabic numerals 1 2 3 4 5 6 7 8 9
roman numerals I II III IV V VI VII VIII IX
10 20 30 40 50 60 70 80 90
X XX XXX XL L LX LXX LXXX XC
100 200 300 400 500 600 700 800 900
C CC CCC CD D DC DCC DCCC CM
1000 2000 3000
M MM MMM

解説

# coding: utf-8
class Integer
  def to_roman
    roman = %w[I V X L C D M]
    to_rom = ""

    puts("1~3999の整数を一つ入力")
    n = gets.to_i

    0.step(to: 4, by: 2) do |i|
      r = n % 10

      case r
      when 1..3
    then to_rom.prepend roman[i] * r   
      when 4
    to_rom.prepend roman[i] + roman[i + 1]
      when 5
    to_rom.prepend roman[i + 1]
      when 6..8
    then to_rom.prepend roman[i + 1] + roman[i] * (r - 5)
      when 9
    to_rom.prepend roman[i] + roman[i + 2]
      end

      n = n / 10
      if n == 0
    break
      end
    end

    to_rom.prepend "M" * n
    return to_rom
  end

  num = ARGV[0].to_i
  puts(num.to_roman)
end

  • source ~/grad_members_20f/members/Kazufumi0823/roman_numerals.org
5
0
0

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
5
0