经典算法题之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.

暴力算法:

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;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值