6. Number of set bit

 

      Ex :   19

//--------------------type -1

 19 & 1 =   1  0  0  1  1

             &  0  0  0  0  1

                  0  0  0  0  1  ( count ++)

19 >> 1 = 9

9 & 1 = 1 0 0 1

         &  0 0 0 1

              0 0 0 1  ( count++)

9 >> 1 = 4

4  & 1  = 1 0 0  

           &  0 0 1

                0 0 0

4 >> 1 = 2

2  & 1  = 1  0  

           &  0  1

                0  0

 

2 >> 1 = 1

1  & 1  = 0  1  

           &  0  1

                0  1 ( count++)

 

Set bits = 3

 

 

 

 

//--------------Type -2 : p & (p-1)

Ex : 19  

step = 1

19  =      1 0 0 1 1

18  =  & 1 0 0 1 0 

               1 0 0 1 0 ( = 18 )  

 

step = 2

18  = 1 0 0 1 0

17  = 1 0 0 0 1

      = 1 0 0 0 0  ( = 16 )

 

step = 3

16 = 1 0 0 0 0

15 = 0 1 1 1 1

     = 0 0 0 0 0 (= 0 )

 

Set bits = 3

 


             Code :

        cnt=0;

        cin>>n;

        int p=n;     

        while(n>0)//-------type-1------

        {

            if((n&1)>0) //n%2>0

            {

                cnt++;

            }

            n=n>>1;

        }

        cout<<"total:"<<cnt<<endl;

        cnt=0;      

        while(p>0)//-------type-2----------

        {

            cnt++;

            p=p&(p-1);

        }

        cout<<"total:"<<cnt<<endl;





Comments