[WXM] LeetCode 201. Bitwise AND of Numbers Range C++

201. 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.

Example 1:

Input: [5,7]
Output: 4

Example 2:

Input: [0,1]
Output: 0

Approach

  1. 题目大意是返回m和n范围内的所有数字进行与操作的结果。这道题不是模拟题,如果直接按题意模拟必然会超时,多举几个例子会发现,题目是要求你找它们二进制的公共前缀,这里贴两种代码,一个是比较通俗易懂但效率一般的代码,还有一个需要推敲但效率极高的代码。

Code

One

class Solution {
public:
	int rangeBitwiseAnd(int m, int n) {
		if (m == n)return m;
		int len = 0, tm = m, tn = n;
		while (tm > 0 && tn > 0) {
			tm >>= 1;
			tn >>= 1;
			++len;
		}
		if (tn != 0)return 0;
		int ans = 0;
		for (int i = len - 1; i >= 0; --i) {
			int a = ((m >> i) & 1), b = ((n >> i) & 1);
			if (a == b) {
				ans |= (a << i);
			}
			else {
				break;
			}
		}
		return ans;
	}
};

Two

class Solution {
public:
	int rangeBitwiseAnd(int m, int n) {
		if (!m)return 0;
		unsigned int s = UINT_MAX;
		while ((m&s) != (n&s)) {
			s <<= 1;
		}
		return s&m;
	}
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值