15. check power of four .

 

40  = 1      = 0000001      = 1bit

41  = 4      = 0000100      = 3bit

42  = 16    = 0010000      = 5bit

43  = 64    = 1000000      = 7bit

Three observations :

1 . number of set bit for each number is always  = 1

2 . ( n & (n-1) )  == 0

3 . Total bits is always hold odd number of bits

Code :

#include<bits/stdc++.h>

using namespace std;

int main()

{

    int n,i; 

    cin>>n; 

    if((n&(n-1))==0)

    {

        int cnt = 0;

        while(n>0)

        {

           cnt++;

           n= n>>1;

        }

        if(cnt&1)

        cout<<"power of 4\n";

        else cout<<"no\n";

    }

    else cout<<"no\n";  

}




Comments