Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: [5,7] Output: 4
Example 2:
Input: [0,1] Output: 0
Tricks: 根据[m,n]的数据范围,可知在计算机是按原码存储,实际上题目意思是求[m,n]数据表示的前缀,eg:
5: 101
6: 110
7: 111
三个数的前缀为100
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int i = 0;
while (m != n) {
m >>= 1;
n >>= 1;
i ++;
}
return (m << i);
}
};