Bit Manipulation: Counting 1's
How do we count the number of set bits (1-bits) in an integer?
Answer
count = 0
for i in range(32):
if (n >> i) & 1:
count += 1This works by examining all 32 bits of the integer and incrementing the count whenever a bit is set.