Accepted C solution with simple explanation


  • 49
    R
    int rangeBitwiseAnd(int m, int n) {
    	int c=0;
    	while(m!=n){
    		m>>=1;
    		n>>=1;
    		++c;
    	}
    	return n<<c;
    }
    

    the result of a range bitwise is the common 'left header' of m and n.


  • 0
    K
    This post is deleted!

  • 0

    cool!!!!!!!!!!!!!!!!


  • 0
    L

    Brilliant Solution !


  • 0

    What a nice solution! Thank you!


  • 0
    E
    public class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        int diff = n - m + 1;
        int mark =  (int)Math.ceil(Math.log(diff) / Math.log(2));
        
        return ((m & n) >> mark) << mark;
    }
    

    }


  • 1
    S

    Hello redace85, I can understand your code, lets say, m = 5 and n = 7 as given in the input... after 2 right shifts, m and n becomes equal and the c's value is 2. and again, you're performing n << c which returns 4 as expected but what is happening during right shifts, but can you please explain how range bitwise is happening here ? could not get the logic !!


Log in to reply
 

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