1
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

問題

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

code

def roman_numerals(input)
    numerals = [[1000,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],
    [90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]]

    result = ""

    numerals.each do |arabic,roman|
	while input >= arabic do
	    result += roman
	    input -= arabic
	end
    end

return result
end

input = ARGV[0].to_i
print "#{input} : #{roman_numerals(input)}\n"

簡単な解説

以下のサイトを参考にrubyで書いた.

https://eigo.rumisunheart.com/2018/03/30/integer-to-roman-number-converter/

メソッド内の宣言

まず,アラビア数字とローマ数字の対応表を配列(numerals)にする.変換したあとの結果(result)を宣言しておく.このresultにローマ数字を足していく形で答えを作る.

while内でアラビア数字をローマ数字に

入力されたアラビア数字(input)から対応表の配列(numerals)のアラビア数字部分(arabic)を引いていき、引いたアラビア数字に対応するローマ数字(roman)を結果(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

  • source ~/grad_members_20f/members/yoshida/roman_numerals.org
1
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
1
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?