One of the approaches to solve this problem is to simultaneously go through bits of two integers and updating the count of bits that are different but better way is to solve it using XOR functionality.
Approach
For Eg : 40 in binary is 101000 and 61 is 111101 , then number of bit swap required is 3
Input :Two integers
Output: Number of bits to be flipped
Approach
- XOR both integers
- Count the number of set bits in resultant integer
For Eg : 40 in binary is 101000 and 61 is 111101 , then number of bit swap required is 3
Input :Two integers
Output: Number of bits to be flipped
#include <iostream> int main() { int firstInteger,secondInteger,res,flip=0; std::cin>>firstInteger>>secondInteger; res=firstInteger^secondInteger; while ( res>0 ) { if ( res&1==1 ) { flip++; } res >>=1; } std::cout<<flip; getchar(); } Please comment if you find anything incorrect.
No comments:
Post a Comment