-
Notifications
You must be signed in to change notification settings - Fork 1
/
binarygap.go
35 lines (32 loc) · 710 Bytes
/
binarygap.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package goexercises
import (
"strconv"
"strings"
)
// BinaryGap - https://codility.com/programmers/lessons/1-iterations/binary_gap/
// Find longest sequence of zeros in binary representation of an integer.
func BinaryGap(n int) int {
// Binary representation of n
binary := strconv.FormatInt(int64(n), 2)
// Remove trailing zeros
binary = binary[:strings.LastIndex(binary, "1")+1]
// Check if binary contains zeros
if !strings.ContainsAny(binary, "0") {
return 0
}
return countGaps(binary)
}
func countGaps(s string) int {
var max, counter int
for _, char := range s {
if char == '0' {
counter++
if counter > max {
max = counter
}
} else {
counter = 0
}
}
return max
}