Last active
April 8, 2018 02:07
-
-
Save thdaraujo/66a9fd3396ea76d3c8290f4ccbdd0944 to your computer and use it in GitHub Desktop.
Calculates the max binary gap of an integer.
This file contains 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
# Returns the maximum binary gap of a number. | |
# e.g.: max binary gap of 529 (1000010001 in binary) is 4. | |
# | |
def max_binary_gap(n) | |
return 0 if (n < 1) | |
result = n.to_s(2).scan(/10+1/).map{|m| | |
m.gsub('1', '').size | |
}.select{|gap| | |
gap >= 0 | |
}.max | |
result || 0; | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment