Problem Statement
What is the efficient way to count number of set bits (1s) in a 32‐bit integer?
Explanation
Brian Kernighan’s algorithm repeatedly does x = x & (x-1) which clears the lowest set bit each time. This runs in O(k) where k = number of set bits, often much less than 32.
Code Solution
SolutionRead Only
int count=0; while(x!=0){ x &= (x-1); count++; } return count;