Skip to main content
PreparationZone Logo
PreparationZone
Back to Fundamentals

Fundamentals · Medium · Free

Count set bits in an integer — Brian Kernighan's trick.

FresherFundamentalsData Structures & Algorithms
Model answer

Brian Kernighan

java
int countBits(int n) {
  int c = 0;
  while (n > 0) { n &= (n - 1); c++; }
  return c;
}

Each n & (n-1) clears lowest set bit—iterations = set bit count.

Also know Integer.bitCount exists but explain the trick.