201. Bitwise AND of Numbers Range

来源:互联网 发布:gcf软件 编辑:程序博客网 时间:2024/06/08 18:56

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.

5:101     6:110       7:111    4:100

从最高位开始相同的bits


int rangeBitwiseAnd(int m, int n) {

    //取第i位上的bit:(x>>i)&1
    //置n的每一位为1或者0:int n|=(1<<i) //即第i位置为1
    int i=0;
    while(m != n){
        m>>=1;//右移一位
        n>>=1;
        i++;
    }
    return m<<i;
}
原创粉丝点击