I used n&(n-1), but, attention the 0.
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && !(n&(n-1));
}
};
@Booky
power of 2 always get 1 at the leftmost bit and 0s at other bits.
So n-1 get every bit 1 if n is power of 2, n&(n-1) equals to 0 (false).s
In other cases it is not going to be all zeros.
@Booky
the aim of n&n-1 is to clear the lowest bit
in other word , it set the lowest bit is 0, if now n==0,then n is the pow of two
@Booky eg. 0x100&0x011 = 0x000 , power of 2 is always like 0x100 0x1000 0x10 0x1 ,!(n&(n-1)) always true;