问题描述:
世界上有10种人,一种懂二进制,一种不懂。那么你知道两个int32整数m和n的二进制表达,有多少个位(bit)不同么?
输入例子:
1999 2299
输出例子:
7
我的代码:
/**
* 求两个数的二进制中不同的位数
* @param m
* @param n
* @return 返回不同的位数的个数
*/
public static int countBitDiff(int m, int n) {
//异或
int ans = m^n;
//求ans中1的个数
int count = 0;
while(ans != 0){
ans &= (ans -1);
count++;
}
return count;
}
注意通过这道题学习如何求一个数二进制中1的个数