Skip to content

Instantly share code, notes, and snippets.

@bylatt
Created September 22, 2018 17:12
Show Gist options
  • Save bylatt/8ded52c2ce9ca929a47745918ebc769f to your computer and use it in GitHub Desktop.
Save bylatt/8ded52c2ce9ca929a47745918ebc769f to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"strconv"
)
func binaryGap(n int) int {
binStr := string(strconv.FormatInt(int64(n), 2))
longestGap := 0
count := 0
for _, v := range binStr {
if string(v) == "0" {
count++
}
if string(v) == "1" {
if count > longestGap {
longestGap = count
}
count = 0
}
}
return longestGap
}
func main() {
fmt.Println(binaryGap(561892))
fmt.Println(binaryGap(42))
fmt.Println(binaryGap(48))
fmt.Println(binaryGap(49))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment