[Codility/Swift] lesson 1 : BinaryGap
Task description
Solution
First, I convert the input N to a binary string using String(value, radix: 2)
. Then, in a for loop, I check each character of the binary string. During the loop, if the character is "0", I add 1 to the tmp
variable for temporary checking (because it is not yet confirmed as a gap).
At the end of the iteration, if the character is "1", I check if the tmp
value is greater than the cnt
value and update the cnt
variable if it is. I also reset the tmp
value to 0 each time the character is "1".
import Foundation
import Glibc
// you can write to stdout for debugging purposes, e.g.
// print("this is a debug message")
public func solution(_ N : Int) -> Int {
// count for maximum gap
var cnt: Int = 0
var tmp: Int = 0
// Implement your solution here
// binary string value
let bin = String(N,radix:2)
if !bin.contains("0") {
return 0
}
// find maximum value of gap
for s in bin {
if s == "0" {
tmp += 1
} else {
// check tmp is bigger than cnt
if tmp >= cnt {
cnt = tmp
}
tmp = 0
}
}
return cnt
}