![]() |
VOOZH | about |
Given two non-negative numbers m and n. Find the position of rightmost same bit in the binary representation of the numbers.
Examples:
Input : m = 10, n = 9 Output : 3 (10)10 = (1010)2 (9)10 = (1001)2 It can be seen that the 3rd bit from the right is same. Input : m = 16, n = 7 Output : 4 (16)10 = (10000)2 (7)10 = (111)2, can also be written as = (00111)2 It can be seen that the 4th bit from the right is same.
Approach: Get the bitwise xor of m and n. Let it be xor_value = m ^ n. Now, get the position of rightmost unset bit in xor_value.
Explanation: The bitwise xor operation produces a number which has unset bits only at the positions where the bits of m and n are same. Thus, the position of rightmost unset bit in xor_value gives the position of rightmost same bit.
Output:
Position = 4
Time Complexity: O(1)
Auxiliary Space: O(1)
Alternate Approach: Until both the value becomes zero, check last bits of both numbers and right shift. At any moment, both bits are same, return counter.
Explanation: Rightmost bit of two values m and n are equal only when both values are either odd or even.
Output:
Position = 4
Time Complexity: O(1)
Auxiliary Space: O(1)