Skip to content

Instantly share code, notes, and snippets.

@UncleGarden
Created July 29, 2014 09:31
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 UncleGarden/6e0f55baeb121d3737ea to your computer and use it in GitHub Desktop.
Save UncleGarden/6e0f55baeb121d3737ea to your computer and use it in GitHub Desktop.
CareerCup 150
/**
* 5.5 Write a function to determine the number of bits required to convert
* integer A to integer B.
*
* @author Garden
*/
public class CC5_5 {
public static void determine(int a, int b) {
System.out.println(Integer.toBinaryString(a));
System.out.println(Integer.toBinaryString(b));
int count = 0;
//异或,相同为0,不同为1,每一次向右移动一位,如果是1,则累计。得到异或之后的数字中的所有1s。就是A需要转换多少bits变成B。
for (int i = a ^ b; i != 0; i = i >> 1) {
count += i & 1;
}
System.out.println(count);
}
public static void main(String[] args) {
determine(12, 45);
determine(256, 458);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment