Last active
April 9, 2020 03:18
-
-
Save foolem/e6c1e783fd7161c220625ce64cb7e33b to your computer and use it in GitHub Desktop.
Codility- binary gap in ruby
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) | |
binary = n.to_s(2) | |
lengths = [] | |
i = binary.index("1") | |
binary.split("1").length.times do | |
binary[i] = '.' | |
n_i = binary.index("1") | |
return !lengths.empty? ? lengths.max : 0 if !!!n_i | |
binary[n_i] = '.' | |
lengths << n_i - (i + 1) | |
i = n_i | |
end | |
return !lengths.empty? ? lengths.max : 0 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment