![]() |
VOOZH | about |
Given two numbers m and n. Find the position of the rightmost different bit in the binary representation of numbers. It is guaranteed that such a bit exists
Examples:
Input: m = 11, n = 9
Output: 2
Explanation:(11)10 = (1011)2, (9)10 = (1001)2
It can be seen that 2nd bit from the right is differentInput: m = 52, n = 4
Output: 5
Explanation: (52)10 = (110100)2,(4)10 = (100)2, can also be written as = (000100)2
It can be seen that 5th bit from the right is different
Table of Content
Get the bitwise xor of m and n. Let it be xor_value = m ^ n. Now, find the position of rightmost set bit in xor_value. As 0 XOR 1 and 1 XOR 0 equals 1, so if a bit is set in the XOR value then it means that the bits at that position were different in the given numbers
An efficient way to find the rightmost set bit:
For n = 10, which is 00001010 in binary, we can find the position of its rightmost set bit using the expression log2(n & -n) + 1. First, we calculate -n using two's complement by inverting the bits of 10 to get 11110101 and adding 1 to obtain 11110110. Performing (n & -n) gives 00000010, which is 2 in decimal. Taking log2(2) results in 1, and adding 1 gives us 2, indicating that the rightmost set bit of 10 is at position 2 from the right. This method efficiently isolates the rightmost set bit and calculates its position using bitwise operations and logarithms.
5
Time Complexity: O(log2 N), this time complexity is equal to O(1) as one has to check for at most 31 bits only
Auxiliary Space: O(1)
ffs() function searches the first set bit from the right side and then returns the index of that bit (1-based indexing). So we can use this function on the XOR of both the values to get the index of the rightmost different bit
5
Time Complexity: O(log2 N), this time complexity is equal to O(1) as one has to check for at most 31 bits only
Auxiliary Space: O(1)