Leetcode201:
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.
m到n之间的所有数之间与,最后的结果应该是二进制数共有的前几位,例如5,6,7二进制分别为101,110,111结果为100,第一位为1其余为0。解题思路即位找到共有的前几位二进制数:
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int r = 2147483647;
while ((m&r) != (n&r))
{
r = r << 1;
}
return (n&r);
}
};