Problem. Return the number of 1 bits (the Hamming weight) of a 32-bit integer.
Naive — check every bit, O(32)
int hammingWeight(int n) {
int count = 0;
for (int i = 0; i < 32; i++)
count += (n >>> i) & 1; // >>> so the sign bit doesn't smear ones
return count;
}
Use >>> (unsigned shift): with >>, a negative n sign-extends and the loop would over-count. Always 32 iterations regardless of input.
Optimal — Brian Kernighan's, O(set bits)
n & (n - 1) clears the lowest set bit, so the loop runs once per set bit — cheaper for sparse numbers:
int hammingWeight(int n) {
int count = 0;
while (n != 0) {
n &= (n - 1); // remove the lowest set bit
count++;
}
return count;
}
This works correctly for negative inputs without >>> because we never shift — we only mask. n != 0 terminates after exactly popcount(n) iterations.
Production answer
int hammingWeight(int n) {
return Integer.bitCount(n); // typically one CPU POPCNT instruction
}
In real code this is the right answer; in an interview, mention it but be ready to show Kernighan's loop, since they're testing whether you know the trick.
| Operation | Best | Average | Worst | Note |
|---|---|---|---|---|
| Bit-by-bit scan | O(32) | O(32) | O(32) | constant but always 32 steps |
| Kernighan n & (n-1) | O(1) | O(popcount) | O(32) | one step per set bit |
| Integer.bitCount | O(1) | O(1) | O(1) | hardware POPCNT |