您的位置:首页 > 其它

Bitwise AND of Numbers Range

2017-05-09 20:25 351 查看
 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.

Credits:

Special thanks to @amrsaqr for adding this problem and creating all test cases.
解析:
多个连续的数相与的结果就是这些数左边相同的那些位,也即是最大数与最小数左边相同的位

代码:

class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
unsigned int mask=INT_MAX;
while(m!=n)
{
mask<<=1;
m&=mask;
n&=mask;

}
int ans=mask&n;

return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Bitwise AND of Numbe