您的位置:首页 > 产品设计 > UI/UE

[CrackCode] 5.5 Determine the number of bits required to convert integer A to integer B

2014-02-05 06:23 531 查看
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: