Created
April 26, 2022 17:48
-
-
Save Turskyi/819ce94fa2afe357db52073f13f4d8bc to your computer and use it in GitHub Desktop.
Given a roman numeral, convert it to an integer.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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