Thursday, August 31, 2017

231. Power of Two

https://leetcode.com/problems/power-of-two/description/
Solution 1.
    bool isPowerOfTwo(int n) {
        if(n<=0) return false;
        int p = 0;
        while(n){
            p += (n & 1);
            n >>= 1;
        }
        if(p == 1) return true;
        return false;
    }
Solution 2.
    bool isPowerOfTwo(int n) {
        if(n<=0) return false;
        return !(n&(n-1));
    }

No comments:

Post a Comment