Total Hamming Distance问题及解法

来源:互联网 发布:java 计算时间差 分钟 编辑:程序博客网 时间:2024/05/18 17:44

问题描述:

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Now your job is to find the total Hamming distance between all pairs of the given numbers.

示例:

Input: 4, 14, 2Output: 6Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (justshowing the four bits relevant in this case). So the answer will be:HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.

问题分析:

此题是一类组合问题,对于所有值的每一位上0和1的组合数。


过程详见代码:

class Solution {public:    int totalHammingDistance(vector<int>& nums) {int sum = 0;int sumOne,t;int n = nums.size();if (!n) return 0;for (int i = 0; i < 32; i++){ t = 1 << i; sumOne = 0;for (int j = 0; j < nums.size(); j++){sumOne += ((nums[j] & t) >> i);}sum += sumOne * (n - sumOne);}return sum;}};


原创粉丝点击