 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Advertisements
 