Very easy to understand bit manipulation Java solution with explanation


  • 0
    G

    public class Solution {

    public int rangeBitwiseAnd(int m, int n) {
        int and = m & n;
        int xor = m ^ n;
    

    // then we only keep the leftmost bit 1 of xor.

        int num = 0;
        while(xor > 0){
            xor = xor >> 1;
            num++;
        }
        xor = 1 << num;
    

    // We only keep the leftmost common bits of m and n by setting all the 1s of "and" after the bit 1 of "xor" to 0.

        return and - (and % xor);
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.