お題
アラビア数字(arabic numerals)を受け取って,ローマ数字(roman numerals)を返すmethodを書きなさい1.
ローマ数字で使われる文字
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 |
最終
# coding: utf-8
def romanize(number)
a=[1000,900,500,400,100,90,50,40,10,9,5,4,1]
r=["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
roman=[]
number=number.to_i
if (number > 0 and number < 4000) then
for i in 0..12 do
while number>=a[i] do
roman.push(r[i])
number-=a[i]
end
end
else
puts "変換できません"
end
puts roman.join(' ')
end
puts "アラビア数字を入力してください"
n=gets
romanize(n)
発展
整数はInteger classです.hello classを参照して,Integer classを拡張して,
999.to_roman #=> CMXCIX
と返すようにしなさい.
# coding: utf-8
def romanize(number)
a=[1000,900,500,400,100,90,50,40,10,9,5,4,1]
r=["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
roman=[]
number=number.to_i
if (number > 0 and number < 4000) then
for i in 0..12 do
while number>=a[i] do
roman.push(r[i])
number-=a[i]
end
end
else
puts "変換できません"
end
puts roman.join(' ')
end
puts "アラビア数字を入力してください"
n=gets
romanize(n)
参照文献
- source ~/grad_members_20f/members/NobuakiMori/ex_roman_numerals.org
-
"初めてのプログラミング", Chris Pine (著), 西山 伸 (翻訳),オライリー・ジャパン (2006/7/24). ↩