All problems
Count Set Bits
Problem
Count the number of 1 bits in the binary representation of a non-negative integer n.
Use Brian Kernighan's trick, which clears the lowest set bit with the expression n = n & (n - 1), looping exactly popcount times. Return the count as an integer.
Hint
n & (n - 1) removes the lowest set bit, so count how many times you can do it.
Test cases
case 1
in: [0]
expected: 0
case 2
in: [7]
expected: 3
case 3
in: [8]
expected: 1
case 4
in: [255]
expected: 8
case 5
in: [1024]
expected: 1
Starter codePython
def count_set_bits(n):
# Your code here
pass5 test cases · run your code against them in the editor