LeetCode 477: Total Hamming Distance

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 477: Total Hamming Distance相关的知识,希望对你有一定的参考价值。

Note:

1. Very smart way of calculating how many difference from bits: https://en.wikipedia.org/wiki/Hamming_distance#Algorithm_example

2. Another way is counting how many 1s and 0s per bits. Then the contribution of that bit will bt C(1, k) * C(1, n - k).

class Solution {
    public int totalHammingDistance(int[] nums) {
        if (nums.length < 2) {
            return 0;
        }
        
        int result = 0;;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                result += getDistance(nums[i], nums[j]);
            }
        }
        return result;
    }
    
    private int getDistance(int a, int b) {
        int c = a ^ b;
        int result = 0;
        while (c != 0) {
            result++;
            c &= c - 1;
        }
        return result;
    }
}
class Solution {
    public int totalHammingDistance(int[] nums) {
        if (nums.length < 2) {
            return 0;
        }
        
        int result = 0;;
        for (int i = 0; i < 32; i++) {
            int ones = 0;
            for (int j = 0; j < nums.length; j++) {
                ones += (nums[j] >> i) & 1;
            }
            result += ones * (nums.length - ones);
        }
        return result;
    }
}

 

以上是关于LeetCode 477: Total Hamming Distance的主要内容,如果未能解决你的问题,请参考以下文章

477. 汉明距离总和

477. Total Hamming Distance

477. Total Hamming Distance

477. Total Hamming Distance

477. Total Hamming Distance

477. Total Hamming Distance - Medium