Five ways to find the number of 1 in binary

Source: Internet
Author: User

#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 (&LT;&LT;ENDL;COUT&LT;&LT;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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.