Problem: Count the number of bits in an integer (population count).
Method 1: Loop and check each bit. .
count = 0
while n > 0:
count = count + (n & 1)
n = n >> 1
return count
Method 2: Clear lowest set bit repeatedly. where is the number of bits.
count = 0
while n > 0:
n = n & (n - 1)
count = count + 1
return count
Method 3: Built-in functions.
- C++:
__builtin_popcount(n) - Python:
bin(n).count('1') - Java:
Integer.bitCount(n)
Built-ins use hardware instructions and are fastest.