Loading

【leetcode】201. Bitwise AND of Numbers Range

  Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.
  
  范围内的数字按照位数与
  暴力法 超时
class Solution {
public:
    int rangeBitwiseAnd(int left, int right) {
        int res=left;
        for(int i=left+1;i<=right;++i){
            res&=i;
        }
    }
};

 

  [5, 7]里共有三个数字,分别写出它们的二进制为:
  101  110  111
  相与后的结果为100,仔细观察我们可以得出,最后的数是该数字范围内所有的数的左边共同的部分,如果上面那个例子不太明显,我们再来看一个范围[26, 30],它们的二进制如下:
  11010  11011  11100  11101  11110
  发现了规律后,我们只要写代码找到左边公共的部分即可,我们可以从建立一个32位都是1的mask,然后每次向左移一位,比较m和n是否相同,不同再继续左移一位,直至相同,然后把m和mask相与就是最终结果,代码如下:
  
class Solution {
public:
    int rangeBitwiseAnd(int left, int right) {
        //提取left right中左边相同的位
        int res=0;
        while(left!=right){
            left>>=1;
            right>>=1;
            res++;
            
        }
        //left 存储的是相同的bit
        return (left<<res);
    }
};

 

 
posted @ 2021-11-20 14:51  aalanwyr  阅读(11)  评论(0编辑  收藏  举报