roman numerals

theme

Write a method that takes arabic numerals and returns roman numerals [^ pine].

Letters used in Roman numerals

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

Example

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

Last

# 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 "Cannot be converted"
  end

  puts roman.join(' ')
end



puts "Please enter Arabic numerals"
n=gets
romanize(n)

development

Integers are Integer classes. Refer to hello class and extend Integer class to

999.to_roman #=> CMXCIX

Please return.

# 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 "Cannot be converted"
  end

  puts roman.join(' ')
end



puts "Please enter Arabic numerals"
n=gets
romanize(n)

References

[^ pine]: "First Programming", Chris Pine (Author), Shin Nishiyama (Translation), O'Reilly Japan (2006/7/24).


Recommended Posts

roman numerals
roman numerals
roman numerals
roman numerals
roman numerals
Roman Numerals
roman numerals
roman numerals
EX1: roman numerals
Let's solve the roman numerals
Find Roman numerals in Ruby
Convert numbers to Roman numerals in Ruby
roman numerals (I tried to simplify it with hash)