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;
    }
}

 

posted on 2017-09-03 16:15  keepshuatishuati  阅读(101)  评论(0编辑  收藏  举报