Total Hamming Distance
Python
Hard
2 views
Problem Description
Read n integers, total Hamming distance is sum of distances over all pairs (i
Input Format
First line n. Second line n integers.
Output Format
One integer total.
Official Solution
import sys
p=sys.stdin.read().strip().split()
if not p: sys.exit(0)
n=int(p[0])
a=list(map(int,p[1:1+n]))
ans=0
for bit in range(31):
ones=0
for v in a:
ones += (v>>bit)&1
zeros=n-ones
ans += ones*zeros
sys.stdout.write(str(ans))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!