Solution:
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?
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:
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