Skip to content

Instantly share code, notes, and snippets.

@camertron
Last active October 13, 2015 18:17
Show Gist options
  • Save camertron/4236029 to your computer and use it in GitHub Desktop.
Save camertron/4236029 to your computer and use it in GitHub Desktop.
Count 1 bits in integer (Ruby)
# protip: use Ruby 1.9 for block support with Enumerable#count
def count_ones(num)
return 0 if num == 0
digits = Math.log2(num).floor + 1
0.upto(digits).count do |i|
num & (2 ** i) == (2 ** i)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment