N (n-1) N & (-N)
N & (n-1): Change the bitwise of the binary representation of N to 0. Let's look at a simple example:
N = 10100 (Binary), then (n-1) = 10011 = "N & (n-1) = 10000
We can see that the first digit is 0.
After understanding the role of N & (n-1), what applications does it have?
1. Calculate the number of 1 in the binary representation of a certain number
While (n> 0 ){
Count ++;
N & = (n-1 );
}
2. Determine whether a number is a power of 2.
N> 0 & (N & (n-1) = 0)
3. calculate n! The number of prime factor 2.
N! Number of prime factor 2 = [n/2] + [N/4] + [N/8] + ....
The following is a simple example to deduce the process: N = 10101 (binary representation)
Now we track the 1 of the highest bits without considering that the other bits are 0,
In
[N/2] 01000
[N/4] 00100
[N/8] 00010
[N/8] 00001
The sum of all values is 01111 = 10000-1.
We recommend that you use the following code: (10101 )! The number of prime factor 2 is 10000-1 + 00100-1 + 00001-1 = 10101-3 (Binary represents the number of 1)
Generally, n! The number of prime factor 2 is N-(N binary represents the number of 1 in)
N & (-N) in the tree array, lowbit is used to calculate the number of factors in T, such as 2 ^ K, to obtain the rightmost 1 of N, it can be seen that there are several two factors
10: 0000 1010
-10: 1111 0110
10 & (-10) is 0010 = 2 so there is one of the 10 factors, and the 2 ^ K form is 2 ^ 1
8 & (-8) = [1000] = 8. Therefore, 3 of the 8 factors are 2, and 2 ^ K is in the form of 2 ^ 3.
N (n-1) N & (-N)