How to convert an integer to Roman numerals in Scala

1 Answer

0 votes
object IntegerToRoman {
  def intToRoman(num: Int): String = {
    val values  = List(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
    val symbols = List("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")

    // foldLeft accumulates the result and the remaining number
    val (roman, _) = values.zip(symbols).foldLeft(("", num)) {
      case ((acc, n), (value, symbol)) =>
        val count = n / value
        val newAcc = acc + symbol * count
        val newN   = n % value
        (newAcc, newN)
    }

    roman
  }

  def main(args: Array[String]): Unit = {
    println(intToRoman(1994)) 
    println(intToRoman(196)) 
    println(intToRoman(9))  
  }
}



/*
run:

MCMXCIV
CXCVI
IX

*/

 



answered Dec 2, 2025 by avibootz
...