One line C++ solution


  • 12
    D

    The number has to be greater than zero, and just one of its bits is set. Given n, computing n - 1 flips all the trailing 0s and the last 1. So computing n & (n - 1) effectively clears the last 1 bit. And in this case that should give us zero if n is a power of 2.

    class Solution {
    public:
        bool isPowerOfTwo(int n) {
            return n > 0 && !(n & (n - 1));
        }
    };

  • 0
    R

    similar c solution,this problem dose too easy to explain.anyway, if a num is power of 2,it should be larger than 0, and only one bit is 1 out of its 32bits or 64bits. this cover the case of the number 1.so~

    bool isPowerOfTwo(int n) {
    return n>0 && 0==(n&(n-1));
    }


  • 0
    4

    Alternatively,

    return n > 0 && ( n & -n) == n;

    or

    cryptic one :)

    return n > 0 && ! (( 1 << 30 ) % n );


Log in to reply
 

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