- Related Questions & Answers
- Position of rightmost set bit in C++
- Position of rightmost common bit in two numbers in C++
- Position of rightmost bit with first carry in sum of two binary in C++
- Golang Program to find the position of the rightmost set bit
- Find position of the only set bit in C++
- Python Program to Clear the Rightmost Set Bit of a Number
- Position of the K-th set bit in a number in C++
- Get value of the bit at a specific position in BitArray in C#
- Find position of left most dis-similar bit for two numbers in C++
- Update the bit in the given position or Index of a number using C++
- Find letter's position in Alphabet using Bit operation in C++
- Program to check we can reach leftmost or rightmost position or not in Python
- Gets or sets the value of the bit at a specific position in the BitArray in C#
- Print leftmost and rightmost nodes of a Binary Tree in C Program.
- Set the bit at a specific position in the BitArray to the specified value in C#?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

Program to show the implementation of our solution,

#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; }

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

Advertisements