Cracking the coding interview--Q5.5

原文:

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);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值