Skip to content

Instantly share code, notes, and snippets.

@pronebird
Created September 26, 2016 09:02
Show Gist options
  • Save pronebird/fd5055a22b32d3bb3df3fa7245e88956 to your computer and use it in GitHub Desktop.
Save pronebird/fd5055a22b32d3bb3df3fa7245e88956 to your computer and use it in GitHub Desktop.
Binary gap solution in Swift / https://codility.com/programmers/task/binary_gap/
//: Playground - noun: a place where people can play
//: Binary gap solution for https://codility.com/programmers/task/binary_gap/
import UIKit
// use unsigned
func binary_gap(_ number: UInt) -> UInt {
var max_gap: UInt = 0
var current_gap: UInt = 0
var n = number
// division by 2 would produce each of bits right-to-left
// i.e. 1096 in bin is:
// 1 0 0 0 1 0 0 1 0 0 0
// first we divide until we skip all trailing zeroes
while n > 0 && n % 2 == 0 {
n /= 2
}
while n > 0 {
// we divide first since last loop pretty much should have stumbled upon 1
n /= 2
// reset counter and save new gap
if n % 2 == 1 {
if current_gap > max_gap {
max_gap = current_gap
}
current_gap = 0
} else {
// bump counter if we stumble upon 0
current_gap += 1
}
}
return max_gap
}
binary_gap(1096)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment