# 题目

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.

5 0101
6 0110
7 0111
&
0100

# AC代码

class Solution {
public:
//方法一，一次遍历 TLE
int rangeBitwiseAnd1(int m, int n) {

int ret = m;
for (int i = m+1; i <= n; ++i)
{
ret = ret & i;
}//for
return ret;
}

//方法二，采用递归，TLE again！
int rangeBitwiseAnd2(int m, int n) {
if (m == n)
return m;

int mid = (m + n) / 2;
return rangeBitwiseAnd(m, mid) & rangeBitwiseAnd(mid + 1, n);
}

//方法三：
int rangeBitwiseAnd(int m, int n) {
int offset = 0;
while (m && n)
{
//找到最高相同位
if (m == n)
{
return m << offset;
}
m >>= 1;
n >>= 1;
offset++;
}
return 0;
}
};

GitHub测试程序源码

#### leetcode 201: Bitwise AND of Numbers Range

2015-05-22 08:30:16

#### [leetcode] 201.Bitwise AND of Numbers Range

2015-07-18 18:11:56

#### Leetcode201(Bitwise AND of Numbers Range)

2015-08-16 23:44:26

#### LeetCode 821 Card Flipping Game

2018-04-23 20:28:53

#### [LeetCode 201] Bitwise AND of Numbers Range

2015-09-13 13:49:38

#### LeetCode 201 Bitwise AND of Numbers Range

2015-12-07 08:36:28

#### LeetCode #201 Bitwise AND of Numbers Range

2015-08-09 21:33:34

#### LeetCode #201: Bitwise AND of Numbers Range

2016-09-17 17:24:19

#### Leetcode 201 Bitwise AND of Numbers Range

2015-05-25 15:58:31

#### LeetCode(201) Bitwise AND of Numbers Range

2015-08-12 11:10:25

## 不良信息举报

LeetCode（201） Bitwise AND of Numbers Range