# Position of rightmost different bit in C++

In this problem, we are given two numbers N and M. Our task is to find the index of the rightmost different bit in the binary representation of the number.

Let’s take an example to understand the problem,

Input − N = 12 , M = 9

Output − 2

Explanation − (12)2 = 1100 and (10)2 = 1010.

The second bit from right is a different bit.

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

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

N = 12 , M = 9
N^M = 0110.

A rightmost set bit here is at index 2.

## 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 rightDiffBit(int m, int n) {
int diffBit = rightSetBit(m^n);
cout<<diffBit;
}
int main() {
int N = 12, M = 10;
cout<<"Postion of first right different bit of the number "<<N<<" & "<<M<<" is ";
rightDiffBit(N, M);
return 0;
}

## Output

Postion of first right different bit of the number 12 & 10 is 2