Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: [5,7]
Output: 4
Example 2:
Input: [0,1]
Output: 0
难度:medium
题目:
给定范围 [m, n] 0 <= m <= n <= 2147483647, 返回这个范围内所有数的与计算结果。
思路:
m 到 n 之间所有数的位与计算,可归结为找出最左边的不同的位即(1, 0) (0, 1),然后把当前位与之后的位都置成0.
例如,二进制数
ABCD EFGH IGKL MN
1001 0001 1000 01,
1010 0110 1010 00
最左边的不同位为C位,C位及C位之后的位都必然经过0,1 之间的变换,因此位与计算就等于将C位及之后的所有位置成0.
Runtime: 5 ms, faster than 100.00% of Java online submissions for Bitwise AND of Numbers Range.
class Solution {
public int rangeBitwiseAnd(int m, int n) {
int result = m & n;
for (int i = 0; m != n; i++, m >>= 1, n >>= 1) {
if (1 == ((m ^ n) & 1)) {
result = result >> i << i;
}
}
return result;
}
}