leetcode201 (bitwise AND of number range: Brian Kernighan algorithm)

Given a range [m, n], where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range (including the two ends of m, n).

Solution: This problem requires us to find out the public prefix of the binary form of the numbers in the range, and the decimal number represented by the found public prefix is ​​the final result. When looking for a common prefix, our main focus should be on the boundary numbers m and n. As long as the common prefix of m and n is found, it is the common prefix of all numbers. So for this question, we only need to find the common prefix of m and n.

Method 1: Displacement, calculate the displacement of m and n until m and n are equal.

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

Method 2: BK algorithm, use BK algorithm to remove the rightmost digit 1 of n in turn until n is less than m

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

Guess you like

Origin blog.csdn.net/CY2333333/article/details/108208402