数が2のべき乗であるかどうかをテストします.
4819 ワード
#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;
}