Cracking the coding interview--Q5.5
2014-11-24 19:20
267 查看
原文:
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);
}
}
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);
}
}
相关文章推荐
- Cracking the coding interview--Q5.5
- 《Cracking the Coding Interview》——第2章:链表——题目4
- 《Cracking the Coding Interview》——第3章:栈和队列——题目6
- 《Cracking the Coding Interview》——第5章:位操作——题目5
- 《Cracking the Coding Interview》——第9章:递归和动态规划——题目3
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目1
- Cracking The Coding Interview 1.4
- Cracking the coding interview--Q18.1
- Cracking The Coding Interview 3.5
- Cracking The Coding Interview5.2
- Cracking the coding interview--Q2.2
- 《Cracking the Coding Interview》——第8章:面向对象设计——题目10
- 《Cracking the Coding Interview》——第10章:可扩展性和存储空间限制——题目5
- Cracking the coding interview--Q20.10
- 《Cracking the Coding Interview》——第14章:Java——题目2
- 《Cracking the Coding Interview》——第16章:线程与锁——题目4
- 《Cracking the Coding Interview》——第17章:普通题——题目1
- 《Cracking the Coding Interview》——第17章:普通题——题目11
- 《Cracking the Coding Interview》——第18章:难题——题目12
- Cracking the coding interview--Q9.3