您的位置:首页 > 其它

两个二进制整数二进制不同位个数

2017-04-04 14:01 113 查看
题目:两个int32整数m和n的二进制表达,有多少个位(bit)不同

[b]输入例子:[/b]
1999 2299

[b]输出例子:[/b]
7

这道题也没什么好说的了,就是基础的亦或^的使用,然后知道用n =& (n-1)的方法可以得到n的二进制里1的个数就行了。我闲着没事用笨方法又做了一遍(笨方法是真笨,我是有多无聊……)

public class Solution {
/**
* 获得两个整形二进制表达位数不同的数量
*
* @param m 整数m
* @param n 整数n
* @return 整型
*/
public int countBitDiff(int m, int n) {
//亦或^,简单粗暴
int res = m^n;
int count = 0;
while(res!=0) {
res &= (res-1);
count++;
}
return count;

//一个最笨的方法,用它就是顺手练练那些函数……
/*
if(m==n)
return 0;
int count=0;
String m1 = Integer.toBinaryString(m);
char[] a = m1.toCharArray();
char[] b = (Integer.toBinaryString(n)).toCharArray();
if(a.length==b.length) {
for(int i=0; i<a.length; i++) {
if(a[i]!=b[i])
count++;
}
}
else if(a.length>b.length) {
for(int j=0; j<(a.length-b.length); j++)
if(a[j]!='0')
count++;
int c = 0;
for(int i=(a.length-b.length); i<a.length; i++) {
if(a[i]!=b[c])
count++;
c++;
}
}
else {
for(int j=0; j<(b.length-a.length); j++)
if(b[j]!='0')
count++;
int c = 0;
for(int i=(b.length-a.length); i<b.length; i++) {
if(a[c]!=b[i])
count++;
c++;
}
}
return count;
*/
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐