Number range by bit and (bit operation / thinking)

Title: https://leetcode-cn.com/problems/bitwise-and-of-numbers-range/
given range [m, n], where 0 <= m <= n <= 2147483647, return all Bitwise AND of numbers (including m and n endpoints).
Idea: An intuitive solution is to change the different status parts of (n, m) to 0, and you can move right by bit and then move it back to the left. This method is very fast.
And there is another way to use the lowbit of our tree array, as follows.

class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        while(n > m) n &= (n-1);
        return n;
    }
};

Faster approach

class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        return n & ~(allOneAfterhighestBit(m^n));
    }
    int allOneAfterhighestBit(int i) {
        i|=i>>1;         // 1xxxxx...最高位复制了一个1到后面 =>11xxxxx... 有2个1
        i|=i>>2;         // 11xxxx...复制了2位1 => 1111xxxx... 有4个1
        i|=i>>4;         // 1111xxxx...复制了4个1 =>11111111xxx... 有8个1
        i|=i>>8;         // 11111111xxx... 复制了8个1 => 1111111111111111xxx... 有16个1
        i|=i>>16;        // 1111111111111111xxx... 复制了16个1 => 11111111...1111 有32个1
        // 如果i最高位不足8或者16等,操作相当于|0,不变,所以此时的i变成了最高位后全是1x
        return i;
    }

}
Published 152 original articles · praised 2 · visits 6450

Guess you like

Origin blog.csdn.net/weixin_43918473/article/details/104918385