两个整数的 汉明距离 指的是这两个数字的二进制数对应位不同的数量。
给你一个整数数组 nums,请你计算并返回 nums 中任意两个数之间 汉明距离的总和 。
class Solution {public int totalHammingDistance(int[] nums) {int ans = 0;//遍历32位for (int i = 0; i < 32; i++) {//判断每一位上有几个1,几个0,1的个数乘以0的个数就是距离总和//a表示1的个数,b表示0的个数int a = 0;int b = 0;//遍历每一位上有几个0,几个1for(int num : nums) {//右移int tmp = num >> i;//判断是0还是1,0 & 1 = 0 ,1 & 1 = 1if((tmp & 1) == 1){a++;}else{b++;}}ans += a * b;}return ans;}
}