欢迎来到cool的博客
7

Music box

Click to Start

点击头像播放音乐
新博客链接

如何用ruby把阿拉伯数字转化为罗马数字。

class Fixnum
  ROMAN_NUMBERS = {
    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",  
  }

  def roman
    n = self
    roman = ""
    ROMAN_NUMBERS.each do |value, letter|
      roman << letter*(n / value)
      n = n % value
    end
    return roman
  end
end


puts 555.roman

 

# gives

# ["", 1000, "M", [0, 555]]
# ["", 900, "CM", [0, 555]]
# ["", 500, "D", [1, 55]] first time the integer is dividable by the value of the roman
# ["D", 400, "CD", [0, 55]] our result now has the roman D
# ["D", 100, "C", [0, 55]]
# ["D", 90, "XC", [0, 55]]
# ["D", 50, "L", [1, 5]] etc
# ["DL", 40, "XL", [0, 5]]
# ["DL", 10, "X", [0, 5]]
# ["DL", 9, "IX", [0, 5]]
# ["DL", 5, "V", [1, 0]] etc
# ["DLV", 4, "IV", [0, 0]]
# ["DLV", 1, "I", [0, 0]]
# DLV

返回列表