Created
May 1, 2019 19:42
-
-
Save wokkaflokka/500833a620b3ba021e556ee00823b89c to your computer and use it in GitHub Desktop.
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
// Write a function parseBinaryInt() that accepts a string of binary digits and converts the value | |
// to its integer representation. | |
fun parseBinaryInt(num: String): Int { | |
if (!valid(num)) { | |
throw RuntimeException("error") | |
} | |
var sum = 0 | |
var offset = 0 | |
val length = num.length - 1 | |
// 2^(length-offset) * Int.parse(char) | |
for (char in num) { | |
val zeroOrOne: Int = char.toString().toInt() | |
sum += zeroOrOne * pow(2, length - offset) | |
offset += 1 | |
} | |
return sum | |
} | |
fun binStringToInt(binString: String): Int { | |
val length = binString.length - 1 | |
if (valid(num)) { | |
return binString.toCharArray() | |
.map({it.toString().toInt()}) | |
.reduceIndexed({index, acc, digit -> | |
return acc + digit * 2f.pow(length - index) | |
}) | |
} else { | |
throw RuntimeException("Invalid string. Must be non-empty binary string".) | |
} | |
} | |
private fun pow(base: Int, exponent: Int): Int { | |
var total = 1 | |
for (i in 1..exponent) { | |
total *= base | |
} | |
return total | |
} | |
private fun valid(str: String): Boolean { | |
return str.length > 0 && "[0-1]*".toRegex().matches(str) | |
} | |
fun main(args: Array<String>) { | |
println(binStringToInt("111")) // 7 | |
println(binStringToInt("10000")) // 16 | |
println(binStringToInt("1000110")) // 70 | |
println(binStringToInt("11111111")) // 255 | |
try { | |
println(binStringToInt("11BBCCC")) // error | |
} catch (e: Exception) { | |
println(e) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment