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

1
2
3
4
5
6
 bin     dec
101 5
110 6

-------------

100 4

再举一个例子

1
2
3
4
5
6
7
 bin      dec
1000 8
1001 9
1010 10
1011 11
-------------

1000 8

可以看出[m,n]范围内的书按位与的结果为m与n二进制表示左边(高位)的共同部分

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Solution {

// public int rangeBitwiseAnd(int m, int n) {

// int step = 0;
// while(m != n){
// m >>= 1;
// n >>= 1;
// step++;
// }
// return m<<step;
// }

public int (int m, int n) {

int i = 1;
while(m != n){
m >>= 1;
n >>= 1;
i <<= 1;
}
return m*i;
}
}