leetcode No201. Bitwise AND of Numbers Range

来源:互联网 发布:知否什么时候上映 湖南 编辑:程序博客网 时间:2024/06/06 19:56

Question:

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 这个范围内的所有元素相与

Algorithm:Bit Manipulation

我们不妨先举几个例子:

1、m=5(1001),n=5(1001);m-n=0 return 5(1001)        

2、m=6(0110),n=7(0111);m-n=1 reurn  6(0110)

3、m=6(0111),n=8(0100);m-n=2 return 4(0100)

4、m=8(1000),n=15(1111);m-n=7 return 8(1000)

我们可以发现,m-n的最高位决定了result的最低位(这句话不知道怎么说。。。)所以我们只需m&n再把低位置0(置零的位数由m-n决定)

举个例子result为32位的二进制,假设m-n的最高位为2,则result的后两位为0,所以result = m&n&(0xfffffffc) 

Submitted Code:

class Solution {public:    int rangeBitwiseAnd(int m, int n) {    long long int range = n-m;    long long int rangebit=0xffffffff;    while(range)  //使range的二进制位数全变0,高位仍为1    {        rangebit = rangebit << 1;        range /= 2;    }    return m&n&rangebit;    }};

Accepted Solutions Runtime Distribution:






0 0
原创粉丝点击