参考自https://blog.csdn.net/shelling_x/article/details/77749220
摘抄记录下来方便日后学习。
题目:给出n(n<1000)个数,求任意两个数之间二进制表示的位数不同的总数量。
输入:
0<=n<32767。 输入首先为n,然后跟随着n个数,范围[0, 4294967295]
输出:
组合数量
样例输入:
2
9
15
样例输出:
2
思路:二进制中,统计两个数的相应位(bit)相同可以采用异或操作,异或运算结果相同为0不同为1。所以两个数异或的结果中1就是相同位数。
a^=b等价于a=a^b,表示将a和b换算为二进制形式后按位进行异或运算,即遇相同位取0不同位取1。
2的二进制表示为10
3的二进制表示为11
&(与)的结果就是10,就是2
java.util.Scanner—— 详解
https://blog.csdn.net/xxkarina/article/details/77950269
Java代码如下
import java.util.Scanner;
public class MainThere {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long[] arr = new long[n];
for (int j=0;j<n;j++ )
{
arr[j]=sc.nextLong();
}
int sum =0;
for (int i=0;i<n-1;i++ )
{
for (int k=i+1;k<n;k++ )
{
long tempInt = arr[i]^arr[k];
sum += count(tempInt);
}
}
System.out.println(sum);
}
public static int count(long tempInt) {
int count =0;
while (tempInt>0) {
tempInt&=(tempInt-1);
count++;
}
return count;
}
}