class Solution {
public:
    /*
     * @param n: An integer
     * @return: True or false
     */
    bool checkPowerOf2(int n) {
        // write your code here
        if (n <= 0) {
            return false;
        }
        // if n is power of 2, it's binary representation has to be 1000...000 and 
        // (n-1)'s binary representation has to be 0111...111 and their AND bit-wise operation will be 0;
        return (n & (n-1)) == 0;
    }
};

results matching ""

    No results matching ""