测试一个数是不是2的幂次方

#include <iostream>
using namespace std;


bool TestPower(int n)
{
if (n == 1)
return false;
int count = 0;
do
{
if (n & 1 == 1)
{
++count;
if (count > 1)
return false;
}
} while ( (n >>= 1) > 0);

if (count == 1)
return true;
else
return false;
}


int main()
{
int a = 4;
int b = 1024;
int c = 1023;

if (TestPower(a))
cout<<"a is power of 2"<<endl;
else
cout<<"a is not power of 2"<<endl;

if (TestPower(b))
cout<<"b is power of 2"<<endl;
else
cout<<"b is not power of 2"<<endl;

if (TestPower(c))
cout<<"c is power of 2"<<endl;
else
cout<<"c is not power of 2"<<endl;

return 0;
}
原文地址:https://www.cnblogs.com/kex1n/p/2217432.html