[Microsoft] O(1) Check Power of 2

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

Example

For n=4, return true;

For n=5, return false;

思路:2的幂次方(2^n)的二进制表达法只有一位为1,其他位都为0,而(2^n-1)则是和(2^n)对应位置正好不一样

           例如8的二进制1000,7的二进制0111

           因为二者可以进行按位与运算,因为按位与运算只有两位同时为1时,结果才为1,否则为0

注意:参加运算的两个数据,按二进制位进行“与”运算,运算规则:0&0=0;   0&1=0;    1&0=0;     1&1=1

class Solution {
    /*
     * @param n: An integer
     * @return: True or false
     */
    public boolean checkPowerOf2(int n) {
        if(n<=0){
            return false;
        }
        
        return (n&(n-1))==0?true:false;     
    }
};
关于位运算:点击打开链接
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章