Use O(1) time to check whether the integer n is a power of 2.
Sample
Example 1:
Input: 4
Output: true
Example 2:
Input: 5
Output: false
challenge
The (1) team
bool checkPowerOf2(int n) {
if(n <=0 )
return false;
int count = 0;
for (int i = 0; i<31; i++)
{
if ((n >> i) & 1 == 1)
{
count++;
}
}
if (count> 1)
{
return false;
}
return true;
}
void test()
{
int n = 3;
bool ret = checkPowerOf2(n);
}