LeetCode201——数字范围按位与

我的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解题报告:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值