Created
July 29, 2014 09:31
-
-
Save UncleGarden/6e0f55baeb121d3737ea to your computer and use it in GitHub Desktop.
CareerCup 150
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
/** | |
* 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