How to count set bits of an integer in Node.js

2 Answers

0 votes
function count_set_bits(n) {
    let count = 0;
    
    while (n) {
        count += n & 1;
        n >>= 1;
    }
    
    return count;
}
  
 
const n = 49; // 0011 0001
 
console.log(count_set_bits(n));

 
  
/*
run:
  
3
  
*/

 



answered Jul 5, 2024 by avibootz
0 votes
function count_set_bits(n) {
    let count = 0;
     
    for (; n; n >>= 1) {
        count += n & 1;
    }
     
    return count;
}
   
  
const n = 49; // 0011 0001
  
console.log(count_set_bits(n));

 
  
/*
run:
  
3
  
*/

 



answered Jul 5, 2024 by avibootz
...