LeetCode刷题实战201:数字范围按位与
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
题意
示例
示例 1:
输入: [5,7]
输出: 4
示例 2:
输入: [0,1]
输出: 0
解题
class Solution {
public int rangeBitwiseAnd(int m, int n) {
int offset = 0;
for (; m != n; ++offset) {
m >>= 1;
n >>= 1;
}
return n << offset;
}
}
class Solution {
public int rangeBitwiseAnd(int m, int n) {
int offset = 0;
while (n > m) {
n &= (n - 1);
}
return n;
}
}
赞 (0)