Math Fundamentals18 sections · 814 units
Open in Course

Count Bits - Implementation

The code

Here's the complete solution using Brian Kernighan's algorithm:


function countBits(n)
    count := 0
    while n > 0
        n := n & (n - 1)    // Clear rightmost set bit
        count := count + 1
    return count

Each iteration clears one set bit. The loop runs exactly as many times as there are 1s in nn. Time complexity: O(k)O(k) where kk is the number of set bits. Space complexity: O(1)O(1).