countSetBits

Medium · Bit Manipulation · 4 test cases

Given a non-negative integer, count the number of '1's in its binary representation (also known as the Hamming weight).

Examples

countSetBits(5) → 2
countSetBits(7) → 3
countSetBits(16) → 1

Starter code

function countSetBits(n) {

}

Complexity of the optimal solution

Time O(k), space O(1). This solution (Brian Kernighan's algorithm) runs in time proportional to the number of set bits (k), which is very efficient. In each iteration, it unsets the rightmost set bit. Space is constant.

Solve countSetBits in the browser