The beauty of programming: 2.1 calculate the number of 1 in the binary number, 2.1 binary
Suppose there are n
In the past, logn used the division of two remainder methods to describe the complexity of logn.
There is a logv method where the number of v is 1 is less complex than logn.
int Count(int x){int ans = 0;while(x){x &= (x-1);ans++;}return ans;}
Here we use the bitwise Operation x & (x-1) to remove one at a time.
100010001000 & (100010001000-1) = 100010000000
100010000000 & (100010000000-1) = 100000000000
100000000000 & (100000000000-1) = 000000000000
Remove 1 at a time three times in total
Then add
for(int i = s; i; i = (i-1)&s)
This loop enumerates all the subsets of s, for example, S = 10101.
10101-> 10100-> 10001-> 10000-> 00101-> 00100-> 00001-> 00000
In this way, all the subsets of S are enumerated.
This will be used when the status is compressed to DP
1 In the binary number
This method should be relatively simple when we use Shift and one-digit retrieval and judgment. In addition, it can be calculated based on the decimal to binary algorithm. Another way is to format it into a string in the form of % B, so that the binary number becomes a string and can be judged one by one.
1 In the binary number
Change printf and scanf by yourself, so you can become lazy IFU.
# Include <stdio. h>
Void main ()
{
Int n;
Scanf ("% d", & n );
Int nCount = 0;
For (; n! = 0; n = n> 1)
If (n & 1)
++ NCount;
Printf ("% d", nCount );
}