Js used to prove safety brush offor (a binary number)

Title Description

An integer that indicates the number of the output of the binary number 1 in. Wherein a negative number indicates a complement.

Cattle off network link

Thinking

If a non-zero integer, then this is an integer of at least 1. If we subtract the integer 1, then the original integer in the rightmost 1 will be changed to 0, the original becomes (0, then there's a 1 followed if the rightmost) 1 in all 01 will be back. All remaining bits will not be affected.
For example: a binary number 1100, from the third to the right of the number is in a rightmost 1. After subtracting 1, the third becomes 0, it later became two of 0 1 1 while the front remains unchanged, so the result is 1011. We found that the results of minus one is to a rightmost 1 bits are all starting to take backwards. This time the results after the original integer if we then do with the operation and subtract 1 from the original integer rightmost 1 the one who began all the bits will become 0. Such as the 1100 & 1011 = 1000. That put an integer minus 1, and then to do with the original integer arithmetic, the integer will rightmost 1 becomes 0. Then a binary integer of 1 how many, how much can be times such an operation.

js code

function NumberOf1(n)
{
    // write code here
    let count = 0
    while (n != 0){
        count++
        n = n & (n - 1)
    }
    return count
}

Guess you like

Origin www.cnblogs.com/dpnlp/p/yongjs-shua-jian-zhioffor-er-jin-zhi-zhong-yi-de-g.html