A statement to determine whether an integer is a power of 2

Question: Enter an integer to determine whether this number is a power of 2.
Idea: Determine whether the binary of the integer is only one, and determine whether (n-1) & n is equal to 0. If you can't understand, please refer to the number of 1 in my previous article binary .

Code:

#include<iostream>
using namespace std;

int main()
{
    int n;
    cin>>n;
    if((n&(n-1))==0)
        cout<<"true";
    else
        cout<<"false";
    return 0;
}
Published 15 original articles · praised 6 · visits 38

Guess you like

Origin blog.csdn.net/weixin_46165788/article/details/105516372