#include <iostream>using namespace std;//the number of binary 1: For a byte (8bit) variable, the algorithm is required to perform as high as possible//1, for the binary, For the 2 remainder can be obtained this bit is 0 or 1int count1 (int v) {Int num=0;while (v) {if (v%2==1) ++NUM;V=V/2;} Return num;} 2. In addition to 2 available right-shift operation, improve efficiency, determine whether a one is 1 available with to distinguish int count2 (int v) {Int num=0;while (v) {num+= (v&1);v> >=1;} return num; } //this number is 2 of the whole number of powers to Judge int count3 (INT&NBSP;V) { int num=0 ; while (v) { v&= (V-1); ++num;} return num;} &NBSP;&NBSP;//4. Branch statements: Low efficiency int count4 (INT&NBSP;V) { int num=0; switch (v) { case 0: num=0; break; case 1: case 2: case 4: case 8: case 16: case 32: case 64: case 128: num=1; break; case 3: case 6: case 12: //There are other possible num=2;break;} Return num;} &NBSP;//5. Table-checking method int counttable[256]={0,1,1,2,1,2,};int&NBSP;COUNT5 (int v) {return counttable[v];} Int main () {cout<<count1 (3) <<endl;cout<<count2 () <<endl;cout<<count3 (4) < <endl;cout<<count4 (<<ENDL;COUT<<COUNT5) (0) <<endl;return 0;}
This article is from the "Small Stop" blog, please be sure to keep this source http://10541556.blog.51cto.com/10531556/1828031
Five ways to find the number of 1 in binary