**Objective**: Given two numbers x and y. write an algorithm to find the number of bits which are to be flipped to convert number x to y.

**Example**

x = 10, Y = 20
x = 0 1 0 1 0, y = 1 0 1 0 0
So if we need to convert x to y then a) turn on the bits at 2^{nd} and 5^{th} position b) turn off the bits at 1^{st} and 4^{th} position.
Output: 4

**Approach:**

Let’s observe the XOR table

X |
Y |
Result |

0 |
0 |
0 |

0 |
1 |
1 |

1 |
0 |
1 |

1 |
1 |
0 |

- So as we can see that XOR of two numbers will set the bit in result if the bit is set in either in X or Y, not in both.
- Calculate z = x XOR y.
- Count the number of set bits in z. this will be the final answer.

**Code**:

**Output**:

Number of bit needs to be flipped to convert 10 to 20 are: 4

__________________________________________________

**Top Companies Interview Questions..-**

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.

__________________________________________________

### Like this:

Like Loading...

*Related*