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

    Example 1:

    1. Input: [5,7]
    2. Output: 4

    Example 2:

    1. Input: [0,1]
    2. Output: 0

    题意

    将指定范围内所有数字进行按位与操作,返回结果。

    思路

    直接按位与会超时。

    找规律(如下图)可发现,由于是连续数字区间,所以必有一部分末尾位相与后为0,问题就转化为了求m和n二进制形式左半边相同的部分。
    image.png
    可以直接移位求相同部分,也可以使用 191. Number of 1 Bits 中提到的 n = n & (n - 1) 方法来处理。


    代码实现 - 位运算 1

    1. class Solution {
    2. public int rangeBitwiseAnd(int m, int n) {
    3. int count = 0;
    4. while (m != n) {
    5. m >>= 1;
    6. n >>= 1;
    7. count++;
    8. }
    9. return m << count;
    10. }
    11. }

    代码实现 - 位运算 2

    1. class Solution {
    2. public int rangeBitwiseAnd(int m, int n) {
    3. while (m < n) {
    4. n &= (n - 1);
    5. }
    6. return n;
    7. }
    8. }