leetcode-201 Bitwise AND of Numbers Range

这题有很多思路,如果直接从m与到n,会TLE

思路一:

the result of a range bitwise AND is the common 'left header' of m and n.(find the leftmost common digits of m and n)

class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        int commonBit = 0;
        while(m != n){
            m >>= 1;
            n >>= 1;
            commonBit++;
        }
        return m << commonBit;
    }
};

思路二:

当m到n之前如果跨过了1,2,4,8等2^i次方的数字时(即判断m与n是否具有相同的最高位),则会为0,否则顺序将m到n相与

<span style="font-family:Microsoft YaHei;font-size:14px;">class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        int bitm = 0,bitn = 0;
        for(int i = 0; i < 31; i++){
            if(m & (1 << i)) bitm = i;
            if(n & (1 << i)) bitn = i;
        }
        
        if(bitm == bitn){
            int res = m;
            for(int j = m; j < n; j++){ //这个地方之所以不用j <= n,是因为这个测试用例:<span style="color: rgb(85, 85, 85); line-height: 35px;">2147483646, 2147483647</span>
                res = res & j;        //<span class="comment" style="margin: 0px; padding: 0px; border: none; color: rgb(0, 130, 0); line-height: 18px;">2147483647+1 会超过范围</span><span style="margin: 0px; padding: 0px; border: none; line-height: 18px;">  </span>
            }
            res = res & n;
            return res;
        }else{
            return 0;
        }
    }
};</span>

还有一种方法:

n&(n-1)会消除n中最后一个1,如1100000100当与n-1按位与时便会消除最后一个1,赋值给n(这样就减免了很多不必要按位与的过程)

<span style="font-family:Microsoft YaHei;font-size:14px;">class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        while(n > m){
            n &= n - 1;
        }
        return n;
    }
};</span>

参考:http://blog.csdn.net/lu597203933/article/details/44811049

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值