for Robot Artificial Inteligence

68. Bitwise AND of Numbers Range(보통)

|

  • We are given range of numbers m to n. We are asked to find the bitwise and in the given range [m,n].
  • A simple solution would be to go from m to n and do a bitwise and given as following:
int and=0;
for (m;m<=n;m++)
     {
	 and&=m;
	 }

But the solution is not effective and efficient for large range of numbers. So we use bit manipulations for solving this problem. Consider the case where range is given as [5,7]. The representation is given as following:

5 - 0101 6 - 0110 7 - 0111

since we are dealing with and(&) operator any presence of 0 with a 1 gives 0. We loop through the binary representation and in the lsbs of elements m and n if there is a 0 and a 1 then the resultant value is 0, so we shift the elements right till there are equal and count the increments made i.e for each of the shift till both the numbers become equal. When both elements m and n are equal we get the value in the lsb as 1. From the above binary representation of the numbers and range we make the following observations:

  1. The third bit from lsb is common for all the three numbers in the range.
  2. There are zeros in the first and second positions from the lsb so the resultant value will be 0 in that postion. Count is a variable wich keeps a track of number of zeros from the lsb to the case of m==n.

The code is as following

public:
    int rangeBitwiseAnd(int m, int n) {
         int count=0;
       // simple solution is to do bitwise and and return the sum.
      //     for(int i=m;i<=n;i++)
      //               sum&=i;        
		 //      return sum;
        while(m!=n)  // see till both numbers are equal
        {   // right shift both numbers by 1
            m>>=1;
            n>>=1;
            count++;  // increment the count.
        }
		//count gives the number of zero places from the lsb so left shift m by count.
        return m<<count;

        // count^(m)
    }

Right Shift & Left shift

https://www.geeksforgeeks.org/left-shift-right-shift-operators-c-cpp/

Another Explanation

https://gamjatwigim.tistory.com/158

Comments