Different one line java solutions


  • 0
    C

    Someone used bitcount or n&(n-1),both are good solutions.Now,I'll paste my solutions.

    //maybe you ignored this inner method of java
    public static boolean isPowerOfTwo(int n) {
            return n > 0 && Integer.highestOneBit(n) == Integer.lowestOneBit(n) ? true : false;
        }
    

    We can also use " n == (n&(-n))"

    public static boolean isPowerOfTwo(int n){
            return n > 0 && n - (n & -n) == 0;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.