# Two Ways

• ``````public class Solution {
// count all the nums how many 0s and how many 1s, multiply #0s*#1s and then sum all the index
public int totalHammingDistance(int[] nums) {
if (nums == null || nums.length < 2) return 0;
int res = 0;
for (int i = 0; i < 32; i++) {
int one = 0, zero = 0;
for (int j = 0; j < nums.length; j++) {
if ((nums[j] & 1) != 0) one++;
else zero++;
nums[j] >>= 1;
}
res += (zero * one);
}
return res;
}
}
``````

second is better, no change to the input nums, and faster

``````public class Solution {
// count all the nums how many 0s and how many 1s, multiply #0s*#1s and then sum all the index
public int totalHammingDistance(int[] nums) {
if (nums == null || nums.length < 2) return 0;
int res = 0;
for (int i = 0; i < 32; i++) {
int one = 0, zero = 0;
for (int num : nums) {
if ((num & (1 << i)) != 0) one++;
else zero++;
}
res += (zero * one);
}
return res;
}
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.