牛客网2016校招真题在线编程之懂二进制

先对两个数进行位异或,这样能够得到两个数中有多少位是不同的,然后再数一下这个数中有多少位1就可以了。
AC代码:
public class Solution {
/**
* 获得两个整形二进制表达位数不同的数量
*
* @param m 整数m
* @param n 整数n
* @return 整型
*/
public int countBitDiff(int m, int n) {
int k = m ^ n;
int res = 0;
while(k>0){
if( (k & 1) == 1) res++;
k>>=1;
}
return res;
}
}
.


浙公网安备 33010602011771号