4. Number of bits in binary representation .

 

        

        Ex : 18  = 1  0  0  1  0

        Total bits = 5

        One right shift until n > 0

        = 18 >> 1 ,   count = 0

        = 18 / 2        count += 1

        = 9 / 2          count += 2

        = 4 / 2          count += 3

        = 2 / 2          count += 4

        = 1 / 2          count += 5

        Total bits = 5

         

         Code :

       cnt = 0  ;

        while( n > 0 )

        {

           cnt ++ ;

            n = n >> 1 ;

        }

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






Comments