Skip to content

Instantly share code, notes, and snippets.

@Plotist
Last active December 26, 2020 21:19
Show Gist options
  • Save Plotist/bd5032ead00e630f8006d586d0bfee12 to your computer and use it in GitHub Desktop.
Save Plotist/bd5032ead00e630f8006d586d0bfee12 to your computer and use it in GitHub Desktop.
<codility> Binary gap
def solution(n)
# n - integer to calculate binary gap on, constrained
raise ArgumentError.new(
"Expected n to be an integer 'n' where 1 < n < 2,147,483,647"
) if !n || !n.is_a?(Integer) || n < 1 || n > 2147483647
max_length = 0
occurance_count = 0
n.to_s(2).split('').each do |bit|
if bit == "0"
occurance_count = occurance_count + 1
else
if max_length < occurance_count
max_length = occurance_count
end
occurance_count = 0
end
end
# returns longest binary gap
# 0 if there are no binary gaps
max_length
end
p solution(1) # 0
p solution(15) # 0
p solution(1041) # 5
p solution(32) # 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment