My simple java solution(3 lines)


  • 56
    Y

    The idea is to use a mask to find the leftmost common digits of m and n.
    Example: m=1110001, n=1110111, and you just need to find 1110000 and it will be the answer.

    public class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        int r=Integer.MAX_VALUE;
        while((m&r)!=(n&r))  r=r<<1;
        return n&r;
    }
    

    }


  • 3
    T

    Your code is correct, but your description is not.
    The approach is to find the leftmost common digits of m and n, but not "leftmost common digits of all 1's for m and n", E.g. m=1110111, n=1110101 and answer is 1110100 but not 1110000.


  • 0
    Y

    Yes, you are right, thanks!


  • 0
    T

    no worries:)


  • 0
    L

    your case is not right.
    they said 0 <= m <= n <= 2147483647, your case is not right "E.g. m=1110111, n=1110101"


  • 0
    S

    Can you please explain why the right most common bits of the two numbers will give the answer?


  • 5
    C

    My Java solution without confusing AND's with Integer.MAX_VALUE.

    public class Solution {
     public int rangeBitwiseAnd(int m, int n) {
        int count=0;
        while(m!=n) { 
            m=m>>>1; //shift numbers right 
            n=n>>>1; //shift numbers right
            count=count+1; //keep track of Shifts
        }
        return n<<count; //do left shifts with 0 padding and return answer.
     }
    }

Log in to reply
 

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