两个二进制整数二进制不同位个数
2017-04-04 14:01
113 查看
题目:两个int32整数m和n的二进制表达,有多少个位(bit)不同
[b]输入例子:[/b]
[b]输出例子:[/b]
这道题也没什么好说的了,就是基础的亦或^的使用,然后知道用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;
*/
}
}
[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;
*/
}
}
相关文章推荐
- 两个int(32位)整数m和n的二进制表达中,有多少个位(bit)不同
- 二进制中1的个数,二进制奇偶位的二进制序列,一个整数的每一位,两个整数二进制中有多少个不同位
- 求出两个int(32位)整数m和n的二进制表达中,有多少bit位不同
- 两个整数二进制表达中,有多少个位(bit)不同
- 两个int(32位)整数m和n的二进制表达中,有多少个位(bit)不同?
- 编程实现:两个int(32位)整数m和n的二进制表达中,有多少个位(bit)不同?
- 编程实现: 两个int(32位)整数m和n的二进制表达中,有多少个位(bit)不同?
- 两个int(32位)整数m和n的二进制表达中,有多少个位(bit)不同
- 求出两个int(32位)整数m和n的二进制表达中,有多少bit位不同
- 两个int(32位)整数m和n的二进制表达中,有多少个位(bit)不同
- 预处理标识符(两个int整数m和n的二进制表达中,有多少个位(bit)不同)
- 【C】写一个宏将一个数字的奇数位和偶数位交换。实现两个int(32位)整数m和n的二进制表达中,位(bit)不同的个数
- 计算两个整数的二进制中有几个二进制不同
- 给定两个正整数(二进制形式表示)A和B,问把A变为B需要改变多少位(bit)?也就是说,整数A和B的二进制表示中有多少位是不同的?
- 计算两个整数的二进制中有几个二进制不同
- 两个int(32位)整数m和n的二进制表达中,有多少个位(bit)不同
- 1.编程实现: 两个int(32位)整数m和n的二进制表达中, 有多少个位(bit)不同? 输入例子: 1999 2299 输出例子:7
- 两个int(32位)整数m和n的二进制表达中,有多少个位(bit)不同?
- 求两个int(32位)整数m和n的二进制表达中,有多少个位(bit)不同
- 两个int整数m和n的二进制表达有多少个位不同