目录

题目描述:

给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按位与(包含 m, n 两端点)。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

示例 1:

输入: [5,7]
输出: 4

示例 2:

输入: [0,1]
输出: 0

解法:

class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        int step = 0;
        while(m != n){
            m >>= 1;
            n >>= 1;
            step++;
            if(m == 0 || n == 0){
                return 0;
            }
        }
        int res = m;
        while(step--){
            res <<= 1;
        }
        return res;
        // 11
        // 00 + 1 = 01
        // get the right-most one: n&(~n + 1)
        // get the left-most one: reset the right-most one, and the recycle
    }
};
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄