Skip to main content
PreparationZone Logo
PreparationZone
Back to Coding

Coding · Easy · Free

Count set bits (Hamming weight) for an integer

CodingBit ManipulationFresher
Model answer

Approach

  • Loop while n != 0, increment count, n &= n-1.
  • Each iteration removes one set bit.

Java Solution

Java
int hammingWeight(int n) {
    int c = 0;
    while (n != 0) {
        c++;
        n &= (n - 1);
    }
    return c;
}
Complexity
TimeO(k) bits set
SpaceO(1)
Interview tip: Brian Kernighan's algorithm — classic bit trick interview question.