/* 5.6 Conversion: Write a function to determine the number of bits you would need to flip to convert integer A to integer B. EXAMPLE Input: 29 (or: 11101), 15 (or: 01111) Output: 2 */ public class Main { public static void main(String[] args) { System.out.println("Hello World!"); System.out.println(convert(29, 15)); } //要找不同的位置 直接异或 找到1的个数就行; public static int convert(int a, int b) { int count = 0; for(int c = a ^ b; c != 0; c >>= 1) { if((c & 1) == 1) { count++; } } return count; } }
Conversion java 走地牙CTCI 5.6
最新推荐文章于 2021-03-14 19:55:01 发布