201. 数字范围按位与
2020-08-24 本文已影响0人
bangbang2

求m-n的按位与
其实仔细一想:求的是m和n的公共前缀,同时m-n中的各个数前缀肯定一样
1:先搞一个while循环,一旦右移到公共前缀,那么m==n,就跳出循环
2:在循环里不断右移m和n,同时count++。count来记录右移了几位,便于最后的恢复
3:return m<<count

class Solution {
public int rangeBitwiseAnd(int m, int n) {
int count=0;
while(m!=n){
m=m>>1;
n=n>>1;
count++;
}
return m<<count;
}
}