题目描述:

Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.

For example, given the range [5, 7], you should return 4.

思路:

结果初始值设为0,从m,n最高位开始遍历,每次判断m,n当前位是不是都为1,同时判断m,n前面遍历过的位上的值是不是都是一样的(用flag表示),如果当前位同为1,并且flag为真,则把结果的当前位置为1,反之,则不进行任何操作,接着把判断当前位m和n是否一样的结果与flag进行逻辑与运算。

代码:

int rangeBitwiseAnd(int m, int n)
{
    int res = 0;
    bool flag = true;
    unsigned base = 0x80000000;
    for(int i = 0; i < 32; i++)
    {
        if((m & base) && (n & base) && flag)
        {
            res |= base;
        }
        flag = flag && (m & base) == (n & base);
        base >>= 1;
    }
    return res;
}

 

posted on 2015-04-19 21:44  Gavin.Lin  阅读(113)  评论(0编辑  收藏  举报