Groovy web console

subscribe to the feed Subscribe
to this
site

Roman Numbers

Published 1 month ago by Marcello de Sales with tags roman numbers
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
def part(number, digit) {
  return (long)(number % (digit * 10) / digit)
}

def toRoman(number) {
  def ones = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
  def tens = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "LC"]
  def hundreds = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]
  def thousands = ["", "M", "MM", "MMM"]

  return thousands[part(number, 1000)] + hundreds[part(number, 100)] + 
      tens[part(number, 10)] + ones[part(number, 1)]
}

println toRoman(1040)
println toRoman(2368)
println toRoman(3978)