Position of rightmost common bit in two numbers in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two numbers M and N. Our task is to print the position (index) of the rightmost common bit of the two numbers.

Let’s take an example to understand the problem,

Input − N = 4 , M = 7

Output − 3

Explanation − (4)2 = 100 , (7)2 = 111. The rightmost common bit is at index 3.

To solve this problem, we will have to find all the same bits of the numbers. To find all same bits we will find xor of M and N. Then we will find the rightmost bit in the negation of M^N.

This seems a bit complex to understand let’s solve an example using this method.

N = 4 , M = 7
~N^M = 100.

A rightmost set bit here is at index 3.

Example

Program to show the implementation of our solution,

 Live Demo

#include <iostream>
#include <math.h>
using namespace std;
int rightSetBit(int N) {
   int bitIndex = log2(N & -N)+1;
   return bitIndex;
}
void rightSameBit(int m, int n) {
   int diffBit = rightSetBit(~(m^n));
   cout<<diffBit;
}
int main() {
   int N = 4, M = 7;
   cout<<"Postiion of first right same bit of the number "<<N<<" & "<<M<<" is ";
   rightSameBit(N, M);
   return 0;
}

Output

Postiion of first right same bit of the number 4 & 7 is 3
raja
Published on 17-Apr-2020 08:07:28
Advertisements