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

链接: http://leetcode.com/problemset/algorithms/

题解:

一开始采用暴力解,自然超时了。后来想了想,其实每次比较一个位置就可以了变成0以后不可能再变回1,所以能不能转换为一个O(32)的运算。因为从m到n的话其实就等于m + 1 + 1 + 1...  ~ n,假设从101000变换到110000,低5位总会被全部清0, 这样我们只用从最高位往最低位置比较m和n的相同部分就可以了,或者从最低位向最高位比较,假如m和n个位不相等,则向右shift,继续比较十位,以此类推。然而想到这里并没有什么用,还没写code我就去看了discuss...于是得到了答案....要改掉这个坏毛病。

Time Complexity - O(1), Space Complexity - O(1)

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

 

还有另外一种更简练的写法在reference里。就是对n进行末位清0,然后于m进行比较,直到n <= m,然后返回n。

Time Complexity - O(1),Space Complexity - O(1)。

public class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        while(m < n) 
            n = n & (n - 1);
        
        return n;
    }
}

 

二刷:

用了上面的办法。就是把n从最低起清零,然后跟m进行比较,当m >= n的时候,这时候我们找到了一个可能的解,返回n。

我们也可以从高位向低位比较。

Java:

Time Complexity - O(1), Space Complexity - O(1)

public class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        while (m < n) n &= (n - 1);
        return n;
    }
}

 

三刷:

利用末位清零。

Java:

public class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        while (m < n) {
            n &= (n - 1);
        }
        return n;
    }
}

 

 

 

Reference:

http://www.meetqun.com/thread-8769-1-1.html

https://leetcode.com/discuss/32115/bit-operation-solution-java

https://leetcode.com/discuss/32278/8line-c-simple-clear-solution

https://leetcode.com/discuss/32053/accepted-c-solution-with-simple-explanation

https://leetcode.com/discuss/35057/share-my-simple-java-solution

https://leetcode.com/discuss/34918/one-line-c-solution

https://leetcode.com/discuss/53646/simple-and-easy-to-understand-java-solution

 

posted @ 2015-05-11 03:42  YRB  阅读(396)  评论(0编辑  收藏  举报