O(1) Check Power of 2(O(1)时间检测2的幂次)

问题

Using O(1) time to check whether an integer n is a power of 2.

Have you met this question in a real interview? Yes
Example
For n=4, return true;

For n=5, return false;

分析

按位与,都为1时才为1;
按位或,都为0时才为0;
按位异或,相同为0,不同为1;
如果是2的倍数,二进制只有一个1,比它小1的数和它与之后必为0。

代码

class Solution {
    /*
     * @param n: An integer
     * @return: True or false
     */
    public boolean checkPowerOf2(int n) {
        // write your code here
        if(n<=0){
            return false;
        }
        if((n&n-1)==0){
            return true;
        }
        return false;
    }
};

你可能感兴趣的:(O(1) Check Power of 2(O(1)时间检测2的幂次))