Created
September 6, 2017 00:35
-
-
Save thmain/3b0640bbd6b1ac9966f9b185e6d239e7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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