How to count the number of 1 bit in a given number with JavaScript

1 Answer

0 votes
function Count1Bit(n) {
	let count = 0;
 
  	while (n > 0) {
        count += n & 1;
        n >>= 1;
  	}
  	return count;
}
        
        
const n = 95; // 0101 1111
         
const count = Count1Bit(n);
         
console.log("Number of 1 bit = " + count);
 
 
 
 
/*
run:
       
"Number of 1 bit = 6"
       
*/

  

 



answered Sep 13, 2021 by avibootz
edited Dec 4, 2021 by avibootz

Related questions

1 answer 191 views
2 answers 175 views
2 answers 157 views
1 answer 117 views
1 answer 128 views
1 answer 135 views
...