您的位置:首页 > 其它

Leetcode -- Bitwise AND of Numbers Range

2015-09-01 21:16 246 查看
题目:

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.

Credits:

Special thanks to @amrsaqr for adding this problem and creating all test cases.

分析:

将[m, n]里面的数字进行与操作。

思路:

1。 遍历一遍,代码少,结果一定正确,但是会超时。

2。m ^(m+1)^(m+2)^(m+3)……^n, 最后留下来的,就是m和n从高位开始相同的数了。比如:101^110^111, 最后留下来的是100, 110^111^1000, 结果就是0。那么现在的问题就是如何找到相同的高位了。

代码:

class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int num = m;
int res = n-m;
int res1 = ~0;
while(res)
{
res = res >> 1;
res1 = res1 << 1;
}
return num & res1 & n;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息