About java “Error: bad binary operator types”

O(1) Check Power of 2) : bad operand types for binary Operator ‘& ‘”.
First paste the code:
copy code

public class Solution {
    /**
     * @param n: An integer
     * @return: True or false
     */
    public boolean checkPowerOf2(int n) {
        // write your code here
         if(n<=0)
           return false;
         return (n&(n-1)==0)?true:false;
    }
}

Copy the code
Error:
initially suspected an operator problem, but also ruled it out. I always think there is something wrong with the “true” and “false”, but I can’t find it. It turns out that it is really a priority problem and may be affected by the assignment (=) operator, as & “Is higher in priority than” == “, in fact the opposite is true. The identity operator has a higher priority than the bit operator, resulting in “&”; The left hand side is an int, and the right hand side is a Boolean.
so just put “return (n& (n-1)==0)?True, false;” Instead of “return ((n& (n-1))==0)?True, false;” It’ll be ok.

Read More: