原文:
Write a function to determine the number of bits required to convert integer A to integer B.
Input: 31, 14
Output: 2
译文:
写程序计算从整数A变为整数B需要修改的二进制位数。
输入:31,14
输出:2
package chapter_5_BitManipulation;
import java.util.Scanner;
/**
*
* 写程序计算从整数A变为整数B需要修改的二进制位数
*
*/
public class Question_5_5 {
/**
* @param num
* @return
*
* 计算num中二进制表示法1的个数
*
*/
public static int count_one(int num) {
int count = 0;
while(num > 0) {
count ++;
num = num & (num-1); // 把num最低位1置为0
}
return count;
}
/**
* @param x
* @param y
* @return
*
* 首先对x ,y 亦或运算,之后计算结果中1的个数即为结果
*
*/
public static int convert(int x, int y) {
int result = x ^ y;
return count_one(result);
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();
int y = scanner.nextInt();
int num = convert(x, y);
System.out.println("修改位数:" + num);
}
}