Last active
March 27, 2018 12:48
-
-
Save dharshan/295eb2ed59fcae0f5ba1840923988153 to your computer and use it in GitHub Desktop.
Ruby binary gap of an Integer
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 bin_gap(number) | |
bin = number.to_s(2) # convert number to binary | |
zeros = bin.split('1') # extract 0's in binary | |
zeros.reject(&:empty?) # remove if any empty elements | |
zeros.pop if number % 2 == 0 # pop out last 0's | |
return 0 if zeros.empty? | |
zeros.map{ |zero| zero.length }.max # max length from 0's array | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment