题目描述:
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
给定范围,对范围内的所有数取与,其实对于任意某一位,如果对所有数取与结果为1,就表明所有数在这一位都是1。因此,最终的结果就是所有数的左边的相同部分,因为随着数值变化,数值的低位会改变,而没有发生改变的高位就是结果。
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int offset=0;
while(m!=n)
{
m=m>>1;
n=n>>1;
offset++;
}
return m<<offset;
}
};