Given two numbers ‘a’ and b’. Write a program to count number of bits needed to be flipped to convert ‘a’ to ‘b’.
Input : a = 10, b = 20 Output : 4 Binary representation of a is 00001010 Binary representation of b is 00010100 We need to flip highlighted four bits in a to make it b. Input : a = 7, b = 10 Output : 3 Binary representation of a is 00000111 Binary representation of b is 00001010 We need to flip highlighted three bits in a to make it b.
1. Calculate XOR of A and B. a_xor_b = A ^ B 2. Count the set bits in the above calculated XOR result. countSetBits(a_xor_b)
XOR of two number will have set bits only at those places where A differs from B.
Thanks to Sahil Rajput for providing above implementation.
To get the set bit count please see this post: Count set bits in an integer
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Find Next Sparse Number
- Find the maximum subarray XOR in a given array
- Sum of bit differences among all pairs
- Swap two nibbles in a byte
- Find the element that appears once
- Count total set bits in all numbers from 1 to n
- Swap bits in a given number
- Rotate bits of a number
- Find the two non-repeating elements in an array of repeating elements
- Count set bits in an integer
- Write an Efficient C Program to Reverse Bits of a Number
- Position of rightmost set bit
- Program to find whether a no is power of two
- Efficient way to multiply with 7
- Smallest power of 2 greater than or equal to n
Improved By : Mithun Kumar