201. Bitwise AND of Numbers Range

Posted 我的名字叫周周

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了201. Bitwise AND of Numbers Range相关的知识,希望对你有一定的参考价值。

    /*
     * 201. Bitwise AND of Numbers Range
     * 2016-6-7 by Mingyang
     * 这个题目很巧妙的一点就是所有的数都是相邻的数
     * 那么这道题目也就相当于找到最长的公共都是1的位数
     * finding the continuous 1s starting from the most significant position over all the operands,
     * 找到一个全是1的mask,然后一格一格的往左边移动,知道最后两个都相等,这里只计算了m与n,并没有计算其它的
     * 因为每两个之间,必然有一个在那一位上有0,所以直接跳过
     */
    public static int rangeBitwiseAnd(int m, int n) {
        int mask=2147483647;//01111111111111111111111111111111
        while((mask&m)!=(mask&n)){
            mask <<= 1;
        }
        return mask&m;
    }

 

以上是关于201. Bitwise AND of Numbers Range的主要内容,如果未能解决你的问题,请参考以下文章