码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 477: Total Hamming Distance

时间:2017-09-03 16:38:14      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:hat   wiki   bit   get   smart   ati   another   from   leetcode   

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

标签:hat   wiki   bit   get   smart   ati   another   from   leetcode   

原文地址:http://www.cnblogs.com/shuashuashua/p/7469865.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!