From 27d29594b7a1211d863f38133148842a3285d9e0 Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Sun, 16 Mar 2025 12:59:18 -0600 Subject: 477. total hamming distance --- total_hamming_distance.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 total_hamming_distance.py (limited to 'total_hamming_distance.py') diff --git a/total_hamming_distance.py b/total_hamming_distance.py new file mode 100644 index 0000000..3098372 --- /dev/null +++ b/total_hamming_distance.py @@ -0,0 +1,27 @@ +# 477. Total Hamming Distance + +""" +the hamming distance between two integers is the number of positions at which +the corresponding bits are different. given an integer array 'nums', return +the sum of hamming distances between all the pairs of the integers in 'nums'. +""" + + +class Solution(object): + def totalHammingDistance(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + bits = [[0, 0] for _ in range(32)] + for i in nums: + for j in bits: + j[i % 2] += 1 + i /= 2 + return sum(x * y for x, y in bits) + + +if __name__ == "__main__": + obj = Solution() + print(obj.totalHammingDistance(nums=[4, 14, 2])) + print(obj.totalHammingDistance(nums=[4, 14, 4])) -- cgit v1.2.3