Created
February 24, 2017 04:26
-
-
Save sathiyaseelan/95b1bb0f9addd3d6122742ef5baee067 to your computer and use it in GitHub Desktop.
Count number of set bits in a number (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
#Brian Kernighan’s algorithm | |
def count_set_bits(num) | |
count = 0 | |
while num != 0 | |
num &= (num-1) | |
count += 1 | |
end | |
count | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment