Skip to content

Instantly share code, notes, and snippets.

@thmain
Created September 6, 2017 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/3b0640bbd6b1ac9966f9b185e6d239e7 to your computer and use it in GitHub Desktop.
Save thmain/3b0640bbd6b1ac9966f9b185e6d239e7 to your computer and use it in GitHub Desktop.
public class CountBitsToBeFlipped {
public int calculate(int x, int y){
//xor of 2 numbers, the bit will be in the result if that bit is set in either x or y
//so by doing xor we will get all the bits which needs to be flipped to convert x to y
int z = x ^ y;
int count =0;
while (z>0){
count += z & 1;
z >>= 1;
}
return count;
}
public static void main(String[] args) {
CountBitsToBeFlipped c = new CountBitsToBeFlipped();
int x = 10;
int y = 20;
System.out.println("Number of bit needs to be flipped to convert " + x + " to " + y + " are: " + c.calculate(x,y));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment