Power of 2 means only one bit of n is '1', so use the trick n&(n-1)==0 to judge whether that is the case
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=0) return false;
return !(n&(n-1));
}
};
try return (n&(n-1)) ==0;
n & (n-1)==0 is executed as n & ((n-1)==0) which I am sure is not what you want.
See https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B
@jeffrey_leo said in Using n&(n-1) trick:
return n > 0 && (n & (~n + 1)) == n;
Hi,
This might be more concise,
return n > 0 && (n & -n) == n;