Codility Challenge : Find longest sequence of zeros in binary representation of an integer (Binary gap)
In this post Swift 5.0 solution given for the Codility exercise. Solving Binary gap for given positive integer. For example, number 9 has binary representation 1001 and contains a binary gap of length 2.
Complete details of exercise : https://app.codility.com/programmers/lessons/1-iterations/binary_gap/
Here is the working solution:
public func solution(_ N : Int) -> Int {
var max_gap: UInt = 0
var current_gap: UInt = 0
// 1
let binSequence = Array(String(N, radix: 2))
var index = 0
while index < binSequence.count {
// 2
if binSequence[index] == "1" {
// 3
if current_gap > max_gap {
max_gap = current_gap
}
current_gap = 0
}
else {
current_gap = current_gap + 1
}
index += 1
}
return Int(max_gap)
}
print(solution(9)) // prints 2
- Create a string representing the given value in base 2 for the given number N
- Either start with new gap -or- end of new gap.
- Track & save the maximum gap.
Thanks for reading till end. Please comment if you find useful or better solutions.