Power button: 231.2 power

Insert picture description here
Solution:
Insert picture description here
You will find through the above picture: a number as long as it is a power of 2. Then after n times divided by 2, the result is 1
and the result of this number for the remainder of 2 is always 0.
Then the code is as follows:

bool isPowerOfTwo(int n){
    
    
    if(n==0)
        return false;
    while(n%2==0)
    {
    
    
        n=n/2;
    }
    if(n==1)
    {
    
    
        return true;
    }
    else
    {
    
    
        return false;
    }
}

So is there a more clever way?
Insert picture description here
With the above picture, you will find that as long as it is a power of 2, the binary result is the first 1 and the back is 0.
Then there will be the following rules:
Insert picture description here
Through the above picture, you will summarize the following The law:
As long as a number n is a power of 2, then: n&(n-1) is equal to 0

code show as below:

bool isPowerOfTwo(int n){
    
    
    if(n<=0)
        return false;
    if(n==1)
        return true;
    if(n&(n-1))
    {
    
    
        return false;
    }
    else
    {
    
    
        return true;
    }
}

The summary of this article comes from: https://www.bilibili.com/video/BV13s41197Ub

Guess you like

Origin blog.csdn.net/qq_46527915/article/details/115033965