Problem Description:
For unsigned integer variables of one byte (8bit), the number of "1" in the second binary representation is required, which requires the efficiency of the algorithm to be executed as efficiently as possible.
In the process of writing programs, depending on the actual application, the requirements for storage space or efficiency are different. For example, on the PC and on the embedded device programming, there is a big difference.
Analysis and Solution:
Solution One:
Give a eight-bit binary example to analyze. For binary operations, we know that by dividing by one 2, the original number will be reduced by one 0. If there is more than one process, then there is a 1 in the current position.
Take 10100010 as an example:
The first time divided by 2 o'clock, the quotient is 1010001, the remainder is 0.
The second time divided by 2 o'clock, the quotient is 101000, the remainder is 1.
Therefore, it is possible to consider the use of Integer data division, by dividing and judging the value of the remainder to analyze.
1 intBitcount (unsignedintN)2 {3Unsignedintc =0;//counter4 while(n)5 {6 if(n% 2 = =1)//the current bit is 17C + +;//counter plus 18n = n/2;9 }Ten returnC; One}
Solution two: Using bit manipulation
Reading Note One: Finding the number of 1 in a binary number