输入:
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的二进制表示为103的二进制表示为11&(与)的结果就是10,就是2
备注:网上笔试题,代码是参考网上别人的,具体出处找不到了,请谅解。摘抄记录下来方便日后学习。如果有问题尽请批评指正,希望可以和大神一起交流。
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; } }