Write a function to determine the number of bits required to convert integer A tointeger B
Input: 31, 14Output: 2
=========
Analysis:
Basic idea of mine is to compare each digits between A and B, and count the different times.
public class Answer {
public static int countDiff(int a, int b){
int count = 0;
int index = 0;
if(a<0 || b< 0) return -1;
while(index<32){
if(((1<<index)&a) != ((1<<index)&b)) count++;
index++;
}
return count;
}
public static void main(String[] args) {
int a = 217;
int b = 532;
System.out.println(a + ": " + AssortedMethods.toFullBinaryString(a));
System.out.println(b + ": " + AssortedMethods.toFullBinaryString(b));
int nbits = countDiff(a, b);
System.out.println("Required number of bits: " + nbits);
}
}
Another ides (from the book) is to use XOR between A and B. Result of which stores all the different digits. Then we can simply count the '1' digits in the result.
public class Question {
public static int bitSwapRequired(int a, int b) {
int count = 0;
for (int c = a ^ b; c != 0; c = c >> 1) {
count += c & 1;
}
return count;
}
public static void main(String[] args) {
int a = 217;
int b = 532;
System.out.println(a + ": " + AssortedMethods.toFullBinaryString(a));
System.out.println(b + ": " + AssortedMethods.toFullBinaryString(b));
int nbits = bitSwapRequired(a, b);
System.out.println("Required number of bits: " + nbits);
}
}