Total Hamming Distance

题目1 : Total Hamming Distance

时间限制:10000ms

单点时限:1000ms

内存限制:256MB

描述

The Hamming Distance between two integers is the number of different digits between their binary representation. For example the hamming distance between 4(=01002) and 14(11102) is 2.

Given N integers, A1, A2, ... AN, find out the total hamming distance of all pairs of them.  

输入

The first line contains an integer N.  

The second line contains N integers denoting A1, A2, ... AN.

For 80% of the data: 1 <= N <= 1000

For 100% of the data: 1 <= N <= 100000 1 <= Ai <= 1000000000

输出

The total hamming distance

样例输入

扫描二维码关注公众号,回复: 4788811 查看本文章
3  
1 2 3

样例输出

4

标程的做法是按位来做。对于每一个二进制位,统计一下N个数中,有几个在这一位是0,有几个在这一位是1。假设有x个是0,y个是1,那么在这一位的产生的距离就是xy。如果我们把32个二进制位看成是常数,那么时间复杂度是O(N)的。

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int count = scan.nextInt();
        long[] array = new long[count];
        for (int i = 0; i < count; i++) {
            array[i] = scan.nextLong();
        }
        long result = 0;
        for (int i = 0; i < 63; i++) {
            long countOne = 0;
            long countZero = 0;
            for (int j = 0; j < count; j++) {
                if ((array[j] & (1L << i)) != 0) {
                    countOne++;
                } else {
                    countZero++;
                }
            }
            result += countOne * countZero;
        }
        System.out.println(result);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38970751/article/details/85530357