function countSetBits(n: number): number {
let count = 0;
while (n > 0) {
n = n & (n - 1);
count++;
}
return count;
}
console.log(countSetBits(29));The number 29 in binary is 11101, which has 4 set bits. Brian Kernighan's algorithm removes one set bit per iteration, so the loop runs 4 times.
n = n & (n - 1) do to the binary representation of n?The expression n & (n - 1) removes the rightmost set bit from n. This is the key step in Brian Kernighan's algorithm to count set bits efficiently.
function countSetBits(n: number): number {
let count = 0;
while (n !== 0) {
n = n & (n + 1);
count++;
}
return count;
}
console.log(countSetBits(2));The code uses n & (n + 1) instead of n & (n - 1). This does not clear the rightmost set bit and can cause an infinite loop because n may never become zero.
function countSetBits(n: number): number {
let count = 0;
while (n > 0) {
n = n & (n - 1);
count++;
}
return count;
}
console.log(countSetBits(1023));1023 in binary is 1111111111 (ten 1s). The algorithm counts all set bits, so the output is 10.
Brian Kernighan's algorithm reduces the number of iterations to the count of set bits by clearing one set bit each loop, making it faster especially for numbers with few set bits.
