Find the total number of bits needed to be flipped to convert a given integer to another.

For example,

Input:
 
x = 65 (which is 01000001 in binary)
y = 80 (which is 01010000 in binary)
 
Output: The total number of bits to be flipped is 2

Practice this problem

The idea is to take XOR of the given two integers. After calculating the XOR, the problem will reduce to counting set bits in the XOR output.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

65 in binary is 01000001
80 in binary is 01010000
 
The total number of bits to be flipped is 2

Java


Download  Run Code

Output:

65 in binary is 1000001
80 in binary is 1010000
 
The total number of bits to be flipped is 2

Python


Download  Run Code

Output:

65 in binary is 0b1000001
80 in binary is 0b1010000
 
The total number of bits to be flipped is 2

Suggested Read: https://graphics.stanford.edu/~seander/bithacks.html