我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/bitwise-and-of-numbers-range/description/
题目描述:
知识点:位运算
思路一:暴力破解法
对于32位整数,确定每一位的值是0还是1。对于每一位的值我们需要遍历[m, n]中的数字,确定这些数字中的相应位是否存在0。
时间复杂度是O(m - n)。空间复杂度是O(1)。
JAVA代码:
public class Solution {
public int rangeBitwiseAnd(int m, int n) {
int result = 0;
for(int i = 0; i < 32; i++){
int temp = 1;
for(int j = m; j <= n; j++){
temp &= j >> i;
if(0 == temp || j == Integer.MAX_VALUE){
break;
}
}
result += temp << i;
}
return result;
}
}
LeetCode解题报告:
思路二:如果m和n不相等,那么[m, n]范围内一定既包含奇数也包含偶数
既然[m, n]范围内既包含奇数也包含偶数,那么其末位与的结果一定是0。
时间复杂度和空间复杂度均是O(1)。
JAVA代码:
public class Solution {
public int rangeBitwiseAnd(int m, int n) {
if(m == 0){
return 0;
}
int temp = 1;
while(m != n){
m >>= 1;
n >>= 1;
temp <<= 1;
}
return m * temp;
}
}
LeetCode解题报告: