My two one-line solutions


  • 0
    K

    Since we know that in any power of two only the first bit will be set. We can either count the bits or and with one smaller number.

    public boolean isPowerOfTwo(int n) {
    return !(n <= 0 || Integer.bitCount(n) != 1);
    }

    public boolean isPowerOfTwo(int n) {
    return !(n <= 0 || n & (n-1));
    }


Log in to reply
 

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