9. The number of 1s in the binary system

subject

Enter an integer and output the number of 1s in the binary representation of the number. Where negative numbers are represented by complements.

Analysis

This is a question of examining binary system

Binary or Operator (OR): The sign is |, indicating that if both binary bits are 0, the result is 0, otherwise it is 1.

Binary and Operator (AND): The sign is&,which means if both binary bits are 1, the result is 1, otherwise it is 0.

Binary No Operator (not): The sign is ~, which means inverting a binary bit.

Exclusive OR Operator (xor): The sign is, indicating that if the two binary bits are not the same, the result is 1; otherwise, it is 0

The left shift operator m << n means that m is shifted left by n bits. when m is shifted left by n bits, the leftmost n bits will be discarded and n zeros will be added to the rightmost, for example:

00001010<<2 = 00101000

Right shift operator m >> n means that m is shifted right by n bits. when m is shifted right by n bits, the rightmost n bits will be discarded and n zeros will be added to the leftmost, for example:

00001010>>2 = 00000010

We can sum the target number with a number.

The number compared by this user must have only one digit that is 1 and the other digit that is 0, so as to know whether this digit of the target number is 0.

Therefore, the initial value of this number used for comparison is 1. After comparison, shift 1 to the left by 1 bit, so as to compare whether all bits are 1 in turn.

Code

function NumberOf1(n)
{
let flag = 1;
let count = 0;
while(flag){
if(flag & n){
count++;
}
flag = flag << 1;
}
return count;
}