477. Total Hamming Distance II

Input: nums = [4,14,2]
Output: 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).
The answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
Input: nums = [4,14,4]
Output: 4
class Solution:
def totalHammingDistance(self, nums: List[int]) -> int:
val=0
cnt=0
for i in range(len(nums)-1):
for j in range(i,len(nums)):
val=nums[i]^nums[j]
while(val):
cnt+=(val&1)
val>>=1
return(cnt)
class Solution:
def totalHammingDistance(self, nums: List[int]) -> int:
total=0
for i in range(32):
ones,zeros,=0,0
for j in range(len(nums)):
if(nums[j]&1==1):
ones+=1
else:
zeros+=1
nums[j]>>=1
total+=ones*zeros
return total

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dhanarajappu

Dhanarajappu

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.