This post is completed by 1 user
|Add to List|
Number of bit to be flipped to convert one number to another.
Objective: Given two numbers x and y. write an algorithm to find the number of bits that are to be flipped to convert the number 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 1stand 4thposition. Output: 4
Let’s observe the XOR table
- So as we can see that XOR of two numbers will set the bit in the result if the bit is set in either 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.
Number of bit needs to be flipped to convert 10 to 20 are: 4
- All elements appears thrice and one element appears once. Find that element in O(n) time and O(1) space Hard