Skip to content

Instantly share code, notes, and snippets.

@wokkaflokka
Created May 24, 2019 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wokkaflokka/42c2bc7c1388f9ac0e8e8cd9989850bc to your computer and use it in GitHub Desktop.
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
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