My one line c solution


  • 1
    bool isPowerOfTwo(int n) {
        return n > 0 && !(n & (n-1));
    }
    
    1. the n must bigger than 0,if it is power of two.
    2. if n is power of two , the binary representation of n will be 1……0 , there will be zero or more zero after 1,and only zero after 1. So n - 1 will be all 1. for example , the binary representation of 16 is 10000, 15 is 1111,so 10000 & 1111 will be zero.

Log in to reply
 

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