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-30

はじめに

今回は以下の記事にある,アラビア数字を受け取って,ローマ数字を返す関数to_romanをrubyで実装する.

roman numerals

境界値が沢山あってifだらけになってしまうような場合は,配列に境界値を入れてループで回すという実装テクニックが使える場合がある.今回はこの方法が有効なので使う.

roman_numerals.rb
def to_roman(n)
  raise RangeError if n <= 0 or 4000 <= n

  arabic_num = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
  roman_num = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
  ret = ""
  arabic_num.zip(roman_num) do |arabic, roman|
    while n >= arabic do
      n -= arabic
      ret << roman
    end
  end
  return ret
end

発展課題

この関数をIntegerクラスのメソッドとして追加してみる.

roman_numerals.rb
class Integer
  def to_roman
    n = self
    raise RangeError if n <= 0 or 4000 <= n

    arabic_num = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
    roman_num = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
    ret = ""
    arabic_num.zip(roman_num) do |arabic, roman|
      while n >= arabic do
	n -= arabic
	ret << roman
      end
    end
    return ret
  end
end

すると以下のように使える.

roman_numerals.rb
3999.to_roman # => "MMMCMXCIX"

  • source ~/grad_members_20f/members/ryuta-kikuchi/qiita_articles/roman_numerals.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?