判断一个整数是否是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;
}

运行结果如下图:

posted @ 2020-07-29 13:51  jackie_astro  阅读(267)  评论(0编辑  收藏  举报