Monday, August 6, 2012

Give a one-line C expression to test whether a number is a power of 2

Ans. //( (x > 0) && ((x & (x - 1)) == 0) )

#include <iostream>
using namespace std;

int main()
{
    int x;
    cout << "enter the no of : ";
    cin >> x;
   
    if( (x > 0) && ((x & (x - 1)) == 0) )
    {
        cout <<"no is power of 2";
    }
   
    else
    {
        cout <<"no is not a power of 2";
    }
   
}

No comments:

Post a Comment