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

目標

Rubyを使い,アラビア数字をローマ数字に変換するプログラムを作成する.

以下はローマ数字で使われる文字です.

arabic numerals roman numerals
1 I
5 V
10 X
50 L
100 C
500 D
1000 M

以下は例になります.

arabic numerals roman numerals
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

解説

まずは1桁から始めます.気を付けることは4,5,9です.

def convert(input)
  while input > 0 do 
    if input == 9
      puts "IX"
      input = input-9
    elsif input == 5
      puts "V"
      input = input-5
    elsif input == 4
      puts "IV"
      input = input-4
    elsif input >=1
      if input == 1
	puts "I"
      else
	print "I"
      end
      input = input-1
    end
  end
end

convert(2)
convert(4)
convert(5)
convert(6)
convert(9)

出力は以下の通りです.

II
IV
V
IV
IX

先ほどのコードの部分に加えて4桁まで(4000未満)判別できるようにします.

ここでも気を付ける部分は4,5,9が含まれている数字です.

def convert(input)
  while input >= 0 do
    if input >= 4000
      puts "error"
      input = -1
    elsif input >= 1000
      print "M"
      input = input - 1000
    elsif input >= 900
      print "CM"
      input = input - 900
    elsif input >= 500
      print "D"
      input = input - 500
    elsif input >= 400
      print "CD"
      input = input - 400
    elsif input >= 100
      print "C"
      input = input - 100
    elsif input >= 90
      print "XC"
      input = input -90
    elsif input >= 50
      print "L"
      input = input - 50
    elsif input >= 40
      print "XL"
      input = input - 40
    elsif input >= 10
      print "X"
      input = input - 10
    elsif input >= 9
      print "IX"
      input = input-9
    elsif input >= 5
      print "V"
      input = input-5
    elsif input >= 4
      print "IV"
      input = input-4
    elsif input >= 1
      print "I"
      input = input-1
    else
      puts " "
      input = -1
    end
  end
end

test = [1, 2, 4, 5, 6, 9, 10, 11, 14, 15, 19, 38, 42, 49, 51, 97, 99, 439, 483, 499, 732, 961, 999, 1999]
test.each do |input|
  puts " #{convert(input)}"
end

出力は以下の通りです.(ローマ数字,アラビア数字の順になっています)

I
II
IV
V
VI
IX
X
XI
XIV
XV
XIX
XXXVIII
XLII
XLIX
LI
XCVII
XCIX
CDXXXIX
CDLXXXIII
CDXCIX
DCCXXXII
CMLXI
CMXCIX
MCMXCIX

caseや配列などを使えばコードも短くなりそうです.

参考にしたサイト

この記事を書くために以下のサイトを参考にしました.roman numerals


  • source ~/grad_members_20f/members/Takahiro-Nishikawa/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?