Coding · Easy · Free
Count set bits (Hamming weight) for an integer
CodingBit ManipulationFresher
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 | |
|---|---|
| Time | O(k) bits set |
| Space | O(1) |
Interview tip: Brian Kernighan's algorithm — classic bit trick interview question.