Roman to Integer

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

Please read the above updated description carefully.

val map: Map[Char, Int] = Map[Char, Int](
  'M' -> 1000,
  'D' -> 500,
  'C' -> 100,
  'L' -> 50,
  'X' -> 10,
  'V' -> 5,
  'I' -> 1
)

/**
  *
  * @param s
  * @return
  */
def romanToInt(s: String): Int = {
  var ret, prev, current = 0
  for (c <- s.reverse) {
    current = map(c)
    if (prev > current) ret -= current
    else {
      ret += current
      prev = current
    }
  }
  ret
}

romanToInt("MMMDCCXLV")

Last updated