Skip to content

Instantly share code, notes, and snippets.

@thdaraujo
Last active April 8, 2018 02:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save thdaraujo/66a9fd3396ea76d3c8290f4ccbdd0944 to your computer and use it in GitHub Desktop.
Save thdaraujo/66a9fd3396ea76d3c8290f4ccbdd0944 to your computer and use it in GitHub Desktop.
Calculates the max binary gap of an integer.
# 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