You are given two integers, ‘N’ and ‘M’. You are supposed to perform the following operation to convert ‘N’ to ‘M’.
In one operation, you can:
1. Choose any bit in ‘N’.
2. Flip the chosen bit, i.e., if the bit is ‘0’, make it ‘1’ and vice versa.
You are supposed to find the minimum number of operations needed to convert ‘N’ to ‘M’.
The first line of input contains an integer 'T’, denoting the number of test cases. The test cases follow.
The first line of each test case contains two integers, ‘N’ and ‘M’.
Output Format:
Print the minimum number of operations needed to convert from ‘N’ to ‘M’.
Print the output of each test case in a new line.
1<= T <= 10^4
0 <= N, M <= 10^9
Where ’T’ is the number of test cases and ‘N’,’M’ are the given integers.
Time Limit: 1 sec
2
15 2
30 0
3
4
In the first test case, the binary representation of ‘15’ is 1111, and the binary representation of ‘2’ is 0010, ie.
1111
0010
We can flip the third, first, and a fourth bit of 2 to convert 2 to 15. Hence, the answer is 3.
In the second test case, the binary representation of ‘30’ is 11110, and the binary representation of ‘0’ is 00000, ie.
11110
00000
We can flip the fourth, third, second, fifth bit of 0 to convert 0 to 30.
2
10 1
4 2
3
2
Iterate through every bit of a number and check if they are the same or not.
The idea is to iterate through each bit of the two numbers, and if at any position the bits of N and M are different, we will flip that bit in N.
O(log(max(N,M))), where N and M are the given integers.
As we are iterating through each bit of N and M, there will be log(N) and log(M) bits in N and M, respectively. Hence the overall time complexity is O(log(max(N,M))).
O(1), as we are using constant space.