Practice on Toph

Participate in exhilarating programming contests, solve unique algorithm and data structure challenges and be a part of an awesome community.

Total Hamming Distance

By RasheedAbid · Limits 2s, 1.0 GB

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Now your job is to find the total Hamming distance between all pairs of the given numbers. For example, if the input array is [4, 14, 2], the output will be 6.

Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just showing the four bits relevant in this case). So the answer will be:

HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.


Input starts with an integer T, denoting the number of test cases (0 < T ≤ 10). Each test case consists of two lines. The first line contains a positive integer N, the size of the array (0 < N ≤ 105). The next line contains the N space separated integers a1, a2, … , aN (0 ≤ ai ≤ 1012).


For each test case, print the total hamming distance of the given numbers.


4 14



73% Solution Ratio

BRUR_DivByZeroEarliest, Oct '17

rafi_1703076Fastest, 0.2s

BRUR_DivByZeroLightest, 131 kB

krishnaShortest, 420B


Login to submit

Toph uses cookies. By continuing you agree to our Cookie Policy.