Skip to content

Instantly share code, notes, and snippets.

@Rican7
Created June 27, 2023 22:05
Show Gist options
  • Save Rican7/6551ed36ef17e76a7786cc5178ff204b to your computer and use it in GitHub Desktop.
Save Rican7/6551ed36ef17e76a7786cc5178ff204b to your computer and use it in GitHub Desktop.
Find the longest "Binary Gap" within a positive integer. Where the "binary gap" is defined as a sequence of 0s surrounded by 1s in the binary format of a number.
package main
import (
"fmt"
)
func LongestBinaryGap(n int) int {
longestGap := 0
binN := fmt.Sprintf("%b", n)
inGap := false
currentGapLen := 0
for i, d := range binN {
if d == '0' && inGap {
currentGapLen++
continue
}
if d == '1' {
if inGap {
if currentGapLen > longestGap {
longestGap = currentGapLen
}
currentGapLen = 0
}
hasNextChar := i < len(binN)-1
inGap = hasNextChar && binN[i+1] == '0'
}
}
return longestGap
}
func main() {
for _, n := range []int{1041, 15, 32, 6, 9, 328, 51712, 66561} {
fmt.Println(LongestBinaryGap(n))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment