Last active
October 13, 2015 18:17
-
-
Save camertron/4236029 to your computer and use it in GitHub Desktop.
Count 1 bits in integer (Ruby)
This file contains 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
# 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