One line O(1) bitwise Solution

  • 0

    All the power of two only the MSB is 1 (i.e 10000, 10000000...)
    Extract the last bit which set to 1, if it equal to itself and strictly bigger than 0, then return true.

        public boolean isPowerOfTwo(int n) {
            return (n & ~(n - 1)) == n && n >0? true : false;

Log in to reply

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