Created
February 3, 2022 01:15
-
-
Save dpellegrini/55f6b9fba91acc54dacc94c11c0d98b3 to your computer and use it in GitHub Desktop.
Naïve binary gap implementation 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 binary_gap(n) | |
n.is_a?(Integer) or raise(ArgumentError, 'Must be an Integer') | |
bits = n.digits(2) | |
longest = current = 0 | |
bits.each do |d| | |
if d == 0 | |
current += 1 | |
else | |
longest = current if (current > longest) | |
current = 0 | |
end | |
end | |
longest | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment