Skip to content

Instantly share code, notes, and snippets.

@Turskyi
Created April 26, 2022 17:48
Show Gist options
  • Save Turskyi/819ce94fa2afe357db52073f13f4d8bc to your computer and use it in GitHub Desktop.
Save Turskyi/819ce94fa2afe357db52073f13f4d8bc to your computer and use it in GitHub Desktop.
Given a roman numeral, convert it to an integer.
/*
Given a string, s, that represents a Roman numeral, return its associated integer value.
Ex: s = "DCLII", return 652.
* */
fun romanToInt(s: String): Int {
val map: MutableMap<Char, Int> = mutableMapOf(
'I' to 1, 'V' to 5, 'X' to 10, 'L' to 50, 'C' to 100, 'D' to 500, 'M' to 1000
)
var number = 0
var last = 1000
for (it: Char in s) {
val value: Int = map.getValue(it)
if (value > last) {
number -= last * 2
}
number += value
last = value
}
return number
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment