Skip to content

Instantly share code, notes, and snippets.

@dharshan
Last active March 27, 2018 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dharshan/295eb2ed59fcae0f5ba1840923988153 to your computer and use it in GitHub Desktop.
Save dharshan/295eb2ed59fcae0f5ba1840923988153 to your computer and use it in GitHub Desktop.
Ruby binary gap of an Integer
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