- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

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

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

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,

#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

- Related Questions & Answers
- Position of rightmost set bit in C++
- Position of rightmost different bit 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 left most dis-similar bit for two numbers in C++
- Check whether the two numbers differ at one-bit position only in Python
- Count common prime factors of two numbers in C++
- C++ Program for Common Divisors of Two Numbers?
- Print the kth common factor of two numbers
- Python Program for Common Divisors of Two Numbers
- Java Program for Common Divisors of Two Numbers
- Count of common multiples of two numbers in a range in C++
- Python Program to Clear the Rightmost Set Bit of a Number
- C++ Program for the Common Divisors of Two Numbers?
- Program to count number of common divisors of two numbers in Python

Advertisements