Bitwise AND of Numbers Range

来源:互联网 发布:数据库的两级映像包括 编辑:程序博客网 时间:2024/05/16 05:55

问题描述

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

0 0
原创粉丝点击