計算一個數是不是2的冪

Problem

Given a number, determine whether it is a power of 2

Solution

bool is_power_2(int n)
{
    return ((n & (n-1)) == 0)? true : false;
}

int main(int argc, char *argv[])
{
    for(int i = 0; i < 100; ++i){
        if(is_power_2(i)){
            cout << i << " is a number of 2 power " << endl;
        }
        else{
            cout << i << " is a number of 2 power " << endl;
        }
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章