> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/bit/477.-total-hamming-distance.md).

# 477. Total Hamming Distance

![](/files/iNx6EtKpoLhJwbYOGKt9)

![](/files/mfWzUtTwW7243gc9p6Vz)

time:O(30\*n), n is nums array length

space:O(1)

```java
// Hamming Distance - which the corresponding bits are different. so only count 0 and 1's count

class Solution {
    public int totalHammingDistance(int[] nums) {
        int n = nums.length;
        int res = 0;
        
        for (int i = 0; i < 30; i++) { // 10^9 < 2^30...恩...shif 0~29次 bit
            int c = 0;
            for (int num : nums) {
                c += (num >> i) & 1; // calculate, how many 1 in index i
            }
            // n-c is 0's count
            res += c*(n-c); // 1 and 0's combination is the result , add i bit (0~29), 30 times
        }
        return res;
    }
}
```
