Last active
April 27, 2023 18:52
-
-
Save iafsilva/7675a688ed3ed5c85da0ad6762896462 to your computer and use it in GitHub Desktop.
BinaryGap Solution
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 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