题目如下:
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.
如果单纯循环会超时,这是因为有许多不必要的按位与操作。注意到0和任意与都是0,而n和n-1相与能去掉最后一个1(二进制下),解决代码如下:
int rangeBitwiseAnd(int m, int n) {
while(n >= m)
n = (n & (n-1));
return n;
}