Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Bit Manipulation

Total Hamming Distance

Medium · Bit Manipulation · Asked at Meta, Amazon, Google

The Hamming distance of two numbers is the number of bit positions where they differ. Print the sum of the Hamming distances over all pairs of the array.

Input

First line: n. Second line: n space-separated integers.

Output

The total Hamming distance.

Constraints

Bits are independent. For each bit position, if c numbers have it set, it contributes c × (n − c) differing pairs. 30 passes, O(30 n). The answer can pass 2^31.

Example 1

Input

3
4 14 2

Output

6

Example 2

Input

3
4 14 4

Output

4

Hints

  1. Comparing all pairs is O(n² · 30).
  2. Each bit position contributes independently.
  3. At one bit, a pair differs exactly when one has it set and the other does not.

Approach

For each of the 30 bit positions, count c = how many numbers have that bit set. Pairs that differ there: one from the c ones, one from the n − c zeros, so c · (n − c). Add these over all bits. The total reaches about 7.5 × 10^10 for n = 10^5, so use 64-bit integers.

Complexity: O(30 · n) time · O(1) extra space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<int> a(n);
    for (auto &x : a) cin >> x;
    long long total = 0;
    for (int b = 0; b < 30; b++) {
        long long c = 0;
        for (int x : a) c += (x >> b) & 1;
        total += c * (n - c);
    }
    cout << total << "\n";
    return 0;
}

Python solution

import sys

data = list(map(int, sys.stdin.read().split()))
n = data[0]
a = data[1 : 1 + n]
total = 0
for b in range(30):
    c = sum((x >> b) & 1 for x in a)
    total += c * (n - c)
print(total)

Java solution

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            in.nextToken();
            a[i] = (int) in.nval;
        }
        long total = 0;
        for (int b = 0; b < 30; b++) {
            long c = 0;
            for (int x : a) c += (x >> b) & 1;
            total += c * (n - c);
        }
        System.out.println(total);
    }
}

Solve Total Hamming Distance online · All practice problems