Created
January 31, 2018 00:23
-
-
Save JanVoracek/cb04f9ed8dc6e72147e95a59830cda98 to your computer and use it in GitHub Desktop.
Part of RomanCalculator
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
fun add(first: String, second: String): String { | |
return intToRoman(romanToInt(first) + romanToInt(second)) | |
} | |
// It's important to keep it descending order | |
private val romanMap = linkedMapOf( | |
"M" to 1000, | |
"CM" to 900, | |
"D" to 500, | |
"CD" to 400, | |
"C" to 100, | |
"XC" to 90, | |
"L" to 50, | |
"XL" to 40, | |
"X" to 10, | |
"IX" to 9, | |
"V" to 5, | |
"IV" to 4, | |
"I" to 1 | |
) | |
private fun romanToInt(roman: String): Int { | |
var sum = 0 | |
var previous = 0 | |
for (char in roman.reversed()) { | |
val numValue = romanMap[char.toString()] ?: 0 | |
sum += if (numValue < previous) -numValue else numValue | |
previous = numValue | |
} | |
return sum | |
} | |
private fun intToRoman(n: Int): String { | |
var rest = n | |
var result = "" | |
while (rest > 0) { | |
val biggestRoman = romanMap.entries.first { it.value <= rest } | |
result += biggestRoman.key | |
rest -= biggestRoman.value | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment