Last active
December 26, 2020 21:19
-
-
Save Plotist/bd5032ead00e630f8006d586d0bfee12 to your computer and use it in GitHub Desktop.
<codility> Binary gap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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