Bit Manipulation - Bitwise AND of Numbers Range

https://leetcode.com/problems/bitwise-and-of-numbers-range/

Difficulty: Medium

给出区间[m, n],其中0 <= m <= n <= 2147483647,返回这个区间的所有整数相与的结果

只要m和n不同,那么,它们的最后一位肯定是不同的,因为1是最基本的增量单位。由于输入已经是m不大于n,因此,只需要考虑m与n是否相等即可。下面分别给出递归和迭代的算法。

class Solution {
public:
    // Runtime: 68 ms
    int rangeBitwiseAnd(int m, int n) {
        return n > m ? rangeBitwiseAnd(m >> 1, n >> 1) << 1 : m;
    }

    // Runtime: 68 ms
    int rangeBitwiseAnd2(int m, int n) {
        int b = 0;
        while (m != n) {
            if (m == 0) { // Runtime: 64 ms,m为0时结束循环,返回结果,小优化
                return 0;
            }
            ++b;
            m >>= 1;
            n >>= 1;
        }
        return m << b;

        while (n > m) {
            n &= (n - 1);
        }
        return n;
    }
};

看一些例子

5 – 101 and 7 – 111 –> 100
5 – 101 and 8 – 1000 –> 0
26 – 11010 and 31 – 11111 –> 11000
26 – 11010 and 32 – 100000 –> 0

当n>m时,每次消去n最末尾的1,直到n<=m,这时的n即为所求的结果

// Runtime: 64 ms
class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        while (n > m) {
            n &= (n - 1);
        }
        return n;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值