Bitwise AND of Numbers Range

Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.

Example 1:
Input: [5,7]
Output: 4
 
Example 2:
Input: [0,1]
Output: 0
 
METHOD 1:
 

class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        if(m == 0){
            return 0;
        }
        while(n > m){
            n = n & n-1;
            System.out.println(n);
        }
        
        return  n;
        
    }
}

 

Try it on Leetcode

Here while we are doing BITWISE AND from n, at some point it would be less than m. And at that point whatever m we do BITWISE AND it will be n,


Consider the rxample [5,7]


Take 7 -> 0000 0111 (7) & 0000 0110 (6) -> 0000 0110 (6)
Take 6 -> 0000 0110 (6) & 0000 0101 (5) -> 0000 0100 (4)

At this point it is less than m(i.e.,5), and it exits from loop. Then return n.

Consider if n at that point is doing BITWISE AND it will be again 4.
 0000 0101 (5) & 0000 0100 (4)  = 0000 0100 (4)


METHOD 2:

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

Here, we are going to do right shift both m, n by 1. After doing both right shifts calculate count value.
At some point both m, n will be equal [which will be either 1 or 0] [It can be found only after doing written works with different numbers BITWISE AND operations]. After that, do left shift that count value with m. Finally it will be the result.

0000 0101 (5) >> 1 = 0000 0010 (2)
0000 0111 (7) >> 1 = 0000 0011 (3)
count becomes 1.

0000 0010 (2) >> 1 = 0000 0001(1)
0000 0011 (3) >> 1 = 0000 0001 (1)
count becomes 2.

Then it exits from loop. And finally left shift by 2.
0000 0001 << 2 = 0000 0100 (4) which is the answer.

Comments

Popular posts from this blog

First Unique Character in a String

Balanced Binary Tree

Majority Element

Smallest Range II