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.

思考:只要找到m和n的二進制表示中,最高的不同位

想法

  • 1、利用位操作找到m與n的第一個不同的bit,然後保持高位不變,低位全補0;
    很多實現方法

代碼

public class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        //int result = Integer._MAX_VALUE;

        if(m == n)
            return n;

        int xor = m ^ n;
        int f1 = Integer.highestOneBit(Integer.MAX_VALUE);            
        while((f1 & xor ) == 0)
            f1 = f1 >> 1;

        f1 = f1 | (f1 - 1);

        return m&n&~f1;

    }
}

類似的問題還有Find XOR of all numbers in a given range

You are given a large range [a,b] where ‘a’ and ‘b’ can be typically between 1 and 4,000,000,000 inclusive. You have to find out the XOR of all the numbers in the given range.

相應代碼

long long f(long long a) {
     long long res[] = {a,1,a+1,0};
     return res[a%4];
}

long long getXor(long long a, long long b) {
     return f(b)^f(a-1);
}

解釋:

This is a pretty clever solution – it exploits the fact that there is a pattern of results in the running XORs. The f() function calculates the XOR total run from [0, a]. Take a look at this table for 4-bit numbers:

0000 <- 0 [a]
0001 <- 1 [1]
0010 <- 3 [a+1]
0011 <- 0 [0]
0100 <- 4 [a]
0101 <- 1 [1]
0110 <- 7 [a+1]
0111 <- 0 [0]
1000 <- 8 [a]
1001 <- 1 [1]
1010 <- 11 [a+1]
1011 <- 0 [0]
1100 <- 12 [a]
1101 <- 1 [1]
1110 <- 15 [a+1]
1111 <- 0 [0]
Where the first column is the binary representation and then the decimal result and its relation to its index (a) into the XOR list. This happens because all the upper bits cancel and the lowest two bits cycle every 4. So, that’s how to arrive at that little lookup table.

Now, consider for a general range of [a,b]. We can use f() to find the XOR for [0,a-1] and [0,b]. Since any value XOR’d with itself is zero, the f(a-1) just cancels out all the values in the XOR run less than a, leaving you with the XOR of the range [a,b].

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章