Bitwise AND of Numbers Range in C++

C++Server Side ProgrammingProgramming

Suppose we have a range [m, n] where 0 <= m <= n <= 2147483647. We have to find the bitwise AND of all numbers in this range, inclusive. So if the range is [5, 7], then the result will be 4.

To solve this, we will follow these steps −

  • i := 0

  • while m is not n, then

    • m := m/2, n := n / 2, increase i by 1

  • return m after shifting to the left i times.

Example(C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int rangeBitwiseAnd(int m, int n) {
      int i = 0;
      while(m != n){
         m >>= 1;
         n >>= 1;
         i++;
      }
      return m << i;
   }
};
main(){
   Solution ob;
   cout << (ob.rangeBitwiseAnd(5,7));
}

Input

5
7

Output

4
raja
Published on 02-May-2020 10:35:29
Advertisements