LeetCode 231. Power of Two

Given an integer, write a function to determine if it is a power of two.


Bit Manipulation hacks : https://graphics.stanford.edu/~seander/bithacks.html. It has almost all the bit tricks.

In this case, we need to remember this bit trick : x & ~(x - 1) ---> get the last '1' (from left to right).


// if the number is a power of two, it should be positive first. and there should only have one '1'.

    bool isPowerOfTwo(int n) {
        if(n <= 0) return false;
        int lastBit = n & ~(n - 1);   // get the last 1
        int tmp = n & ~lastBit;       // mask this 1 to 0.
        if(tmp == 0) return true;     // if there is any other 1s, it is not power of 2.
        return false;
    }


Update two: just need to check there is only one '1' in bit representation!~.

    bool isPowerOfTwo(int n) {
        if(n <= 0) return false;
        return (n & (n - 1)) == 0;
    }


 

你可能感兴趣的:(LeetCode 231. Power of Two)