The binary number 1 (to prove safety offer_15)

Title Description


An integer that indicates the number of the output of the binary number 1 in.

n&(n-1)

The removal of n-bit operations bit-level representation in the lowest one who.

n       : 10110100
n-1     : 10110011
n&(n-1) : 10110000

A conclusion

Conclusion: a number minus the number with a result of calculation n&(n-1), the number will right (lower) first 1 to 0, this bit is left unchanged and the (high)

Examples: The results after 1100 such as (corresponding to decimal 12), 1 is subtracted 1011 (i.e. decimal 11), the two numbers after the operation, we found that the final result is 1000 (corresponding to decimal 8, of course, 8 nothing to do with the back, you can skip). We will once for each operation with a 1 is erased, so that the elimination of the last must be 0, so we can use this as loop termination condition in the code.




public int NumberOf1(int n) {
    int cnt = 0;
    while (n != 0) {
        cnt++;
        n &= (n - 1);
    }
    return cnt;
}

Integer.bitCount()
public int NumberOf1(int n) {
    return Integer.bitCount(n);
}

 


Guess you like

Origin www.cnblogs.com/ziytong/p/12111621.html