判断一个整数是否是2的幂
power_two.cpp内容如下:
#include <iostream>
using namespace std;
bool is_power_of_two(unsigned int n)
{
return (n && !(n & (n-1)));
}
int main(int argc, char **argv)
{
const int kRange = 1000;
for (int i = 0; i < kRange; ++i)
if (is_power_of_two(i+1))
cout << i+1 << " is a power of two" << endl;
return 0;
}
运行结果如下图: