Find position of left most dis-similar bit for two numbers in C++

C++Server Side ProgrammingProgramming

In this problem we are given two numbers, num1 and num2. Our task is to find the position of the leftmost dis-similar bit for two numbers. We need to print the first bit which is not the same for both numbers in their respective binary representation. The length of both needs to be the same to find the bit. This is done by appending 0’s to the start of the number with less bits.

Let’s take an example to understand the problem,

Input

num1 = 4, num2 = 7

Output

1

Explanation

Binary representation of 4 is 100

Binary representation of 7 is 111

The first bit is not the same.

Solution Approach

An approach to solve the problem is first equalising the number of bits in both the numbers by multiplying it with 2(bit difference). And the taking XOR of both numbers which will return 1 only at places where their bits are different. So, in this XOR, we will find the first position and then adding 1 to it gives the required position.

Algorithm

Step 1 − Equalise the bits of the numbers by multiplying smaller only by (2 ^ (bit-length difference)).

Step 2 − Perform XOR operation on num1 and num2.

Step 3 − Bit difference is equal to total (bitCount - XORbitCount + 1).

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
#include <math.h>
using namespace std;
int findmisMatchBit(int num1, int num2) {
   if (num1 == num2)
      return 0;
   int num1Size = floor(log2(num1)) + 1;
   int num2Size = floor(log2(num2)) + 1;
   int BitSizeDiff = abs(num1Size - num2Size);
   int maxBitSize = max(num1Size, num2Size);
   if (num1Size > num2Size)
      num2 *= pow(2, BitSizeDiff);
   else
      num1 *= pow(2, BitSizeDiff);
   int XOR = num1 ^ num2;
   int XORBitSize = floor(log2(XOR)) + 1;
   return (maxBitSize - XORBitSize + 1);
}
int main() {
   int num1 = 43, num2 = 765;
   cout<<"The position of leftmost dis-similar bit of the two
   number is "<<findmisMatchBit(num1, num2);
   return 0;
}

Output

The position of leftmost dis-similar bit of the two number is 4
raja
Published on 16-Mar-2021 05:11:33
Advertisements