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.
暴力算法:
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
if(0<=m && m<=n && n<=2147483647) {
int sum=-1;
for(int i=m; i<=n; ++i) {
sum &=i;
if(sum==0)
break;
}
return sum;
}
return NULL;
}
};
以下摘自http://www.meetqun.com/thread-8769-1-1.html
n&(n-1)只会将最后一个1消掉。如101&100=100,1100&1011=1000。
有一个求正整数对应二进制数中1的个数的经典算法:
int count_num(int n) {
int cnt=0;
while( n > 0 ) {
++cnt;
n &= (n-1);
}
return cnt;
}
这个算法的原理是对n通&(n-1)来不断消除末尾的1。
对于题中的要求,如果我们从n一直倒着&到m,则n中的1就会从末尾被逐个消除为0。
举个例子,m=64,n=97,则
01100001 = 97
01100010 = 96
97&96 这一步消除了最后一个1,变成了01100000
01011111 = 95
(97&96)&95这一步消除了倒数第二个1,变成了01000000
此后就是一个很漫长的过程,因为从94 = 01011110开始和01000000进行&操作就不起作用了。
能对01000000起作用的就是00111111=65
所以这一题答案就是01000000 = 64。
此题为什么不能用暴力循环来做,因为做了太多无用功,真正工作的是消除末尾1的动作。
此题和上述数1的个数的问题一样,循环条件该为m<n
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
if(0<=m && m<=n && n<=2147483647) {
while( n > m) {
n &= (n-1);
}
return n;
}
return NULL;
}
};