def count_set_bits(n): count = 0 while n: n &= (n - 1) count += 1 return count print(count_set_bits(29))
The number 29 in binary is 11101, which has 4 set bits (1s). Brian Kernighan's algorithm removes one set bit per iteration, so the loop runs 4 times.
def count_set_bits(n): count = 0 while n: n &= (n - 1) count += 1 return count print(count_set_bits(0))
Zero in binary is 0, which has no set bits. The loop does not run, so count remains 0.
Brian Kernighan's algorithm removes one set bit per iteration, so it runs only as many times as there are set bits, making it faster than checking every bit.
def count_set_bits(n): count = 0 while n > 0: n = n & (n + 1) count += 1 return count print(count_set_bits(4))
The expression n & (n + 1) does not remove set bits correctly and can cause n to never become zero, leading to an infinite loop.
Numbers with exactly 2 set bits between 0 and 15 are: 3(11), 5(101), 6(110), 9(1001), 10(1010), 12(1100). There are 6 such numbers.
