LeetCode201 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.

Example 1:

Input: [5,7]
Output: 4

Example 2:

Input: [0,1]
Output: 0

题源:here

感悟:第一次在线编程,感觉确实需要对数据有非常深的理解才可以啊。

思路:

第一种方法误打误撞竟然还通过测试了:

class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        int range = n-m;
        for(int i = 0;range;range/=2, i++){
            m &= ~(1<<i);
        }
        m &= n;
        return m;
    }
};

这种方法应该是首创吧。。。我首先是认为只要m到n的过程中,有的位出现了变化,那么这些位置肯定就是0了,最后m和n再与一下是为了排除m到n进位的情况。

第二种方法是参考了:here

class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        return n>m?(rangeBitwiseAnd(m/2,n/2)<<1):m;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/88582042