- Related Questions & Answers
- Position of rightmost common bit in two numbers in C++
- Find position of the only set bit in C++
- Find most significant set bit of a number in C++
- 8085 program to find larger of two 8 bit numbers
- 8085 program to find maximum of two 8 bit numbers
- Position of rightmost set bit in C++
- Position of rightmost different bit in C++
- Check whether the two numbers differ at one-bit position only in Python
- Position of rightmost bit with first carry in sum of two binary in C++
- Find max of two Rational numbers in C++
- Find LCM of two numbers
- Find GCD of two numbers
- Find letter's position in Alphabet using Bit operation in C++
- C++ Program for Common Divisors of Two Numbers?
- Golang Program to find the position of the rightmost set bit

- 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, 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,**

num1 = 4, num2 = 7

1

Binary representation of 4 is 100

Binary representation of 7 is 111

The first bit is not the same.

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.

**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,**

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

The position of leftmost dis-similar bit of the two number is 4

Advertisements