I am trying to use C to solve the problem. But I don't know why the following C code doesn't work out. Here is my code. Thanks in advance.
bool isPowerOfTwo(int n) {
if(n<1) return 0;
return n&(n-1)==0 ? 1 : 0;
}
The problem is that ==
has higher precedence than &
, so you need to use parentheses:
return (n&(n-1))==0 ? 1 : 0;