Given two numbers n1 and n2. The task is to find the position of first mismatching bit in the binary representation of the two numbers from left. We need to find this bit after making lengths of binary representations of both numbers same. We make lengths same by appending 0s in the smaller number.
- For Example: n1 = 1, n2 = 7. Bitwise representation of n1 and n4 will be “1” and “111” respectively. Append two zeros to n1 to make it 100.
- Print zero if n1 is equal to n2.
Input: n1 = 12, n2 = 34 Output: 2 Binary representation of 12 is 1100 and of 34 is 100010. First make both representations of the same length by appending 0s. So the first representation now becomes 11000. The second bit is the different bit. Input: n1 = 1, n2 = 2 Output: 2
For finding the position of leftmost dis-similar bit among bit representaion of two numbers, either bit by bit comparison can be done or a derived formula can be used. Although the time complexity for both is same.
For finding the left most dis-similar bit first of all equalize the bit length of both numbers by multiply the smaller one with pow(2, bit-length Difference). After making bit-length equal take XOR of both number. Now, leftmost dis-similar bit is clearly reflected in XOR value. Subtracting the bit-length of XOR value from bit-length of given number plus 1 is the position of leftmost dis-similar bit can be concluded.
- Find bit length of n1 & n2.
- Equalize bit-length of both number by placing zero to right of smaller number (same as multiplying smaller one by pow(2, bit-length Difference) )
- Take XOR of both number
- Difference of bit-length of any number and bit-length of XOR value is required answer plus 1
Below is the implementation of the above approach:
- Position of rightmost common bit in two numbers
- Check whether the two numbers differ at one bit position only
- Find position of the only set bit
- Find the value at kth position in the generated array
- Find letter's position in Alphabet using Bit operation
- Find two numbers from their sum and XOR
- Find the XOR of first N Prime Numbers
- Find XOR of numbers from the range [L, R]
- Find k numbers which are powers of 2 and have sum N | Set 1
- Find average of two numbers using bit operation
- Find the two numbers with odd occurrences in an unsorted array
- Find the count of distinct numbers in a range
- Find Two Missing Numbers | Set 2 (XOR based solution)
- Find N distinct numbers whose bitwise Or is equal to K
- Find Unique pair in an array with pairs of numbers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.