Created
May 24, 2019 18:25
-
-
Save wokkaflokka/42c2bc7c1388f9ac0e8e8cd9989850bc to your computer and use it in GitHub Desktop.
Parses a well-formatted binary string and return it's decimal value, showcasing functional style in kotlin along the way
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
import org.junit.Test | |
import kotlin.math.pow | |
class BinStringTest { | |
@Test | |
fun test() { | |
println(BinaryString("111").toInt()) // 7 | |
println(BinaryString("10000").toInt()) // 16 | |
println(BinaryString("1000110").toInt()) // 70 | |
println(BinaryString("11111111").toInt()) // 255 | |
try { | |
println(BinaryString("11BBCCC").toInt()) // error | |
} catch (e: Exception) { | |
println(e) | |
} | |
} | |
} | |
class BinaryString(private val str: String) { | |
private val exponent = str.length - 1 | |
init { | |
if (str.isEmpty() || !"[0-1]*".toRegex().matches(str)) { | |
throw RuntimeException("Invalid binary string.") | |
} | |
} | |
fun toInt(): Int { | |
return str.toCharArray() | |
.map { it.toString().toInt() } | |
.foldIndexed(0f, {index, acc, digit -> | |
acc + digit * 2f.pow(exponent - index) | |
}) | |
.toInt() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment