Math Fundamentals18 sections · 814 units
Open in Course

Count Bits - Checking Each Position

Loop through all bits

The direct approach: loop through all 32 bit positions (assuming 32-bit integers) and check if each bit is set. Count how many times you find a 1.

For each position ii from 0 to 31, check if (n&(1<<i))0(n \& (1 << i)) \neq 0. If true, increment your count.

This works, but you're always checking 32 bits even if nn has only a few bits set. Can you do better? What if you only looked at the bits that are 1?