Conversion

Posted: 22 Feb, 2021
Difficulty: Easy

PROBLEM STATEMENT

Try Problem

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’.

Input Format:
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.
Constraints:
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
Approach 1

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.

  • Define a variable count and initialize it to 0. We will use this variable to count the number of bits we need to flip to make N equal to M.
  • Iterate through each bit of N and M,
    • Check if the current bit is the same in N and M or not.
      1. If the bits are different, increment count by 1.
  • Return count.

 

Try Problem