LeetCode201—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.
分析
比如说5的二进制是101,7的二进制是111,6的二进制是110,从5按位与到7,最后的结果是:
101 & 111 &110 = 100 也就是4.
按位运算一直不是我的强项,不过这题的规律可以参照:
http://www.cnblogs.com/grandyang/p/4431646.html
代码
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int x=INT_MAX;
for(;;)
{
if((m&x) ==(n&x))
break;
x=x<<1;
}
return m&x;
}
};
还没有评论,来说两句吧...