Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Number of bit to be flipped to convert one number to another.

Objec­tive:  Given two num­bers x and y. write an algo­rithm to find the num­ber of bits which are to be flipped to con­vert num­ber x to y.


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 2nd and 5th position b) turn off the bits at 1st and 4th position.
Output: 4


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 num­bers will set the bit in result if the bit is set in either in X or Y, not in both.
  • Cal­cu­late z = x XOR y.
  • Count the num­ber of set bits in z. this will be the final answer.



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

You may also like...