Easybit-manipulation
Number of 1 Bits
Problem (restated)
Return the number of set bits (Hamming weight) in a 32-bit integer.
Intuition
n &= n-1 clears the lowest set bit; count until n=0.
Approaches
Brian Kernighan
Tested onlyTime O(popcount)Space O(1)
Idea. while n: n&=n-1; c++.
Walkthrough. 11 → 3 (1011).
Trade-offs. n&1 + n>>>1 loop is O(32); Kernighan is O(#bits).
Solution
export function hammingWeight(n: number): number {
let c = 0;
n >>>= 0;
while (n) {
n &= n - 1;
c++;
}
return c;
}
export function hammingWeight(n: number): number {
let c = 0;
n >>>= 0;
while (n) {
n &= n - 1;
c++;
}
return c;
}
Template connection
Bit manipulation set-bit checks.
Reflection
- Which pattern gave this away within 90 seconds?
- What changed from the standard template?
- What would break the current solution?