[RUBY] roman numerals

theme

Write a method that takes arabic numerals and returns roman numerals.

Letters used in Roman numerals

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

test

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
1000 M
3999 MMMCMXCIX

policy

--Check the number of thousands. --Arrange M (number of thousands) --Check the number of hundreds. ――If 5 or more and 9, arrange CM, otherwise arrange D and C (number of hundreds ―― 5). ――If 5 or less is 4, then CD is arranged, otherwise C is arranged (number of hundreds). --Check the number of tens place ――If 5 or more and 9, arrange XC, otherwise arrange L and X (number of tens digit ―― 5). ――If 5 or less is 4, then XL is arranged, otherwise, X is arranged (number of tens). --Check the number of ones place ―― If it is 5 or more and 9, IX is arranged, otherwise V and I are arranged (number of ones place ―― 5). --If 5 or less is 4, then IV is arranged, otherwise I is arranged (number of ones digit).

code

(*) This code converts numbers less than 4000 to Roman numerals.

def roman_numerals (number)

  #Calculate the number of 1000
  thousand = number / 1000
  a = number % 1000
  roman = 'M' * thousand

  #Calculate the number of 100
  hundred = a / 100
  b = a % 100

  if (hundred == 9)
    roman += 'CM';
  elsif (hundred >= 5)
    roman += 'D' + 'C' * (hundred - 5)
  elsif (hundred == 4)
    roman += 'CD'
  else
    roman += 'C' * hundred
  end

  #Calculate the number of 10
  ten = b / 10
  c = b % 10

  if (ten == 9)
    roman += 'XC'
  elsif (ten >= 5)
    roman += 'L' + 'X' * (ten - 5)
  elsif (ten == 4)
    roman += 'XL'
  else
    roman += 'X' * ten
  end

  #Calculate the number of 1
  if (c == 9)
    roman += 'IX'
  elsif (c >= 5)
    roman += 'V' + 'I' * (c - 5)
  elsif (c == 4)
    roman += 'IV'
  else
    roman += 'I' * c
  end

  return roman
end

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

The execution result is

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
1000, M
3999, MMMCMXCIX

Confirmed to match the above test.

I don't have ruby ​​coding ability, so I think the above code still has room for improvement.

Reference page

  1. YOU-GO9's "Roman \ _numerals"

Recommended Posts

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)