I have written a solution for the codility task which is Binary Gap.
finding the highest gap in Binary. for example 1041 is the input number and convert it to binary the result is 5. here is the code :
package codility
import(
"strconv"
)
func Solutions(N int) int{
binary := convertNumberToBinary(N)
result := getHighestGap(binary)
return result
}
func convertNumberToBinary(N int)string{
result := ""
for N > 0 {
binary := N%2;
result = strconv.Itoa(binary) + result
N = N/2;
}
return result
}
func getHighestGap(binary string) int{
result := 0
count := 0
isCount := false
stringArray := []byte(binary)
for i:=0; i < len(stringArray); i++{
if stringArray[i] == '1' {
if result < count{
result = count
}
count = 0
isCount = true
}else if isCount{
//found 0
count ++
}
}
return result
}
and the test file :
package codility
import(
"testing"
)
func TestBinrayGap(testing *testing.T){
var testObjects = []struct{
input int
expected int
}{
{1041, 5},
{529, 4},
{20, 1},
}
for _, t := range testObjects {
actual := Solutions(t.input)
if actual != t.expected{
testing.Errorf("Test failed expected : %s, actual : %s", t.expected, actual)
}
}
}
here I'm converting the input number to binary first and then count the highest length of the gap by converting the string to array byte `[]byte'. And for the test I'm using table driven test.