Bitwise AND of Numbers Range

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.

你可以列出一部分连续数的二进制,也许你会发现2^i次方在其中起得作用,也许你想直接从m &到 n,然而,这并没有什么卵用,所得的结果只能是Time Limited。

下面的方法,慢慢体会:

class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        
        int trans = 0;
        while(m != n) {
            trans ++;
            m >>= 1;
            n >>= 1;
        }
        return n<<trans;
    }
};



你可能感兴趣的:(Bitwise AND of Numbers Range)