官方的解法
然后再配上这个代码就一目了然了
class Solution {public int totalHammingDistance(int[] nums) {int len&#61;nums.length;int[] bitCount &#61; new int[32];if(len <&#61; 1){return 0;}for(int numIndex &#61; 0; numIndex < len; numIndex&#43;&#43;){for(int bitIndex &#61; 0; bitIndex < 32; bitIndex&#43;&#43;){bitCount[bitIndex] &#43;&#61; nums[numIndex] & 1;nums[numIndex] &#61; nums[numIndex] >> 1;if(nums[numIndex] &#61;&#61; 0){break;}}}int oneCount &#61; 0;for(int bitIndex &#61; 0; bitIndex < 32; bitIndex&#43;&#43;){oneCount &#43;&#61; bitCount[bitIndex] * (len - bitCount[bitIndex]);}return oneCount;}
}
上边就是用bitCount [bitIndex] 从第0位累加到32位&#xff0c;分别记录数组中每个数字对应的二进制位&#xff0c;然后用官方提供的那种思维 t*(n-t)记录每一组的汉明距离&#xff0c;最后再把32组累加起来就是总的汉明距离了
int hammingDistance(int x, int y){long long z &#61; (x ^ y);int ret &#61; 0;while (z !&#61; 0) {z &#61; (z & (z - 1));ret&#43;&#43;;}return ret;}int totalHammingDistance(vector<int>& nums){int ret &#61; 0, n &#61; nums.size();for (int i &#61; 0; i < n - 1; i&#43;&#43;) {for (int j &#61; i &#43; 1; j < n; j&#43;&#43;) {ret &#43;&#61; hammingDistance(nums[i], nums[j]);}}return ret;}这是属于暴力求解的方法
再看看官方的解法![在这里插入图片描述](https://img-blog.csdnimg.cn/20200507232753581.png?x-oss-process&#61;image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2RlbGV0ZV9idWc&#61;,size_16,color_FFFFFF,t_70)