Problem:
For any nonnegative integer, the total number of bits 1 is counted in the binary expansion.
Solve:
Related blog:http://www.cnblogs.com/maples7/p/4324844.html
Before reading this article, we can look at the above article, this article mainly discusses its optimization problem.
General Solution:
O (LOGN):
1 intCountones (unsignedintN)2 {3 intones =0;4 while(0<N)5 {6Ones + = (1&n);7N >>=1;8 }9 returnones;Ten}
It's just that every time you take the second binary, the last one is 1 counts.
The efficiency is known by bit operations (the right shift is equivalent to dividing by 2), which is O (LOGN).
Optimization Solution 1:
O (Countones (n)):
1 intCountOnes1 (unsignedintN)2 {3 intones =0;4 while(0<N)5 {6ones++;//count (last at least one is 1)7N &= N-1;//clear the right 1 at the moment.8 }9 returnones;Ten}
The explanations are as follows:
Optimization Solution 2:
O (LOGW), W = O (logn) is the bit width of an integer, which is actually an O (1) algorithm .
Code and Explanation:
This algorithm is a strategy for merging counters. The 32Bit of the input counts as 32 counters, representing 1 numbers per bit. Then merge the adjacent 2 "counter", make I become 16 counters, each counter value is the number of 2 bit 1, continue to merge adjacent 2 "counter", so I becomes 8 counters, each counter value is 4 bit 1 number. And so on, until I becomes a counter, its value is the number of bits in the value of 1 in the I of 32Bit.
From: "Data structure exercises analysis", Deng Junhui
Reference:
1, http://blog.chinaunix.net/uid-21275705-id-224360.html
2, Http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetNaive
optimization of number of digits 1 in statistical binary expansion