Skip to content

Instantly share code, notes, and snippets.

@sathiyaseelan
Created February 24, 2017 04:26
Show Gist options
  • Save sathiyaseelan/95b1bb0f9addd3d6122742ef5baee067 to your computer and use it in GitHub Desktop.
Save sathiyaseelan/95b1bb0f9addd3d6122742ef5baee067 to your computer and use it in GitHub Desktop.
Count number of set bits in a number (ruby)
#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