# 0477. Total Hamming Distance ###### tags: `Leetcode` `FaceBook` `Medium` `Bit Manipulation` Link: https://leetcode.com/problems/total-hamming-distance/ ## 思路 用count array记录所有数字的二进制表示里第i位是1的个数 ans = 对于所有i count[i] * (nums.length - count[i]) 求和 用位运算比不用位运算快很多 而且由于都是int数字,所以可以用31位的array存count number ## Code ```java= class Solution { public int totalHammingDistance(int[] nums) { int[] count = new int[31]; for(int num:nums){ int power = 0; while(num > 0){ count[power] += num & 1; num >>= 1; power++; } } int ans = 0; int size = nums.length; for(int cnt:count){ ans += cnt*(size-cnt); } return ans; } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up