Common:
I am always used to call the common law, because I really can not find a proper name to describe it, in fact, is the simplest way, a little program based on the people are able to think, that is the SHIFT + count, very simple, not much to say, directly on the code, this method of operation of the number of input n is the highest bit 1 of the
intBitcount (unsignedintN) {unsignedintc =0;//counter while(N >0) { if(N &1) ==1)//the current bit is 1++c;//counter plus 1N >>=1;//Shift } returnC;}
A more streamlined version is as follows
int int N) { int c =0// counter for (c =0; n; n >>=1// cyclic shift c + = n &1// if the current bit is 1, the counter plus 1 return C;}
Fast method
This method is faster and has no relation to the size of the input n and is only related to the number of 1 in N. If the binary representation of N has K 1, then this method only needs to loop K times. The principle is to constantly clear n binary representation of the rightmost 1, while accumulating counters, until n is 0, the code is as follows
int int N) { int c =0 ; for (c =0; n; + +c) { &= (n-1// clears the lowest bit of 1 } return C;}
Why is n &= (n–1) able to erase the rightmost 1? Because from the binary point of view, N is equivalent to the lowest bit of n-1 plus 1. For example, 8 (1000) = 7 (0111) + 1 (0001), so 8 & 7 = (+) & (0111) = 0 (0000), the 8 rightmost 1 is cleared (actually the highest 1, because there is only one 8 in the binary of 1). For example, 7 (0111) = 6 (0110) + 1 (0001), so 7 & 6 = (0111) & (0110) = 6 (0110), the rightmost 7 of the binary representation of 1 (that is, the lowest bit 1) is cleared.
Ext.: http://www.cnblogs.com/graphics/archive/2010/06/21/1752421.html
Algorithm-to find the number of 1 in a binary number