Each 1 in the xor will represent one different bit between A and B. We then simply need to count the number of bits that are 1.
1 public static int bitSwapRequired(int a, int b) {
2 int count = 0;
3 for (int c = a ^ b; c != 0; c = c >> 1) {
4 count += c & 1;
5 }
6 return count;
7 }
1 public static int bitSwapRequired(int a, int b) {
2 int count = 0;
3 for (int c = a ^ b; c != 0; c = c >> 1) {
4 count += c & 1;
5 }
6 return count;
7 }
No comments:
Post a Comment