Skip to content

Instantly share code, notes, and snippets.

@iafsilva
Last active April 27, 2023 18:52
Show Gist options
  • Save iafsilva/7675a688ed3ed5c85da0ad6762896462 to your computer and use it in GitHub Desktop.
Save iafsilva/7675a688ed3ed5c85da0ad6762896462 to your computer and use it in GitHub Desktop.
BinaryGap Solution
fun solution(n: Int): Int {
var longestBinaryGap = 0
var currentBinaryGap = 0
var isCounting = false
// Get binary representation
val binaryString = Integer.toBinaryString(n)
for (char in binaryString) {
when {
// If we were already counting means binary gap ended
char == '1' && isCounting -> {
if (currentBinaryGap > longestBinaryGap) {
longestBinaryGap = currentBinaryGap
}
currentBinaryGap = 0
}
// When finding a 1 start counting
char == '1' -> isCounting = true
// When counting -> increment our binary gap
char == '0' && isCounting -> currentBinaryGap++
}
}
return longestBinaryGap
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment