Bitwise AND of Numbers Range 数字范围位相与(Medium)

题目: 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.

仔细观察我们可以得出,最后的数是该数字范围内所有的数的左边共同的部分

 int rangeBitwiseAnd(int m, int n) {
    if(m>n){
        return 0;
    }
    int a = m&n;
    if (a==0||m==n)
        return a;

    int i=0;
    while(m!=n&&m!=0){
        m >>= 1;
        n >>= 1;
        i++;
    }
    return m<<i;
}

results matching ""

    No results matching ""