461. Hamming Distance

TheHamming distancebetween two integers is the number of positions at which the corresponding bits are different.

Given two integersxandy, calculate the Hamming distance.

Note:
0 ≤x,y< 231.

Example:

Input:
 x = 1, y = 4


Output:
 2


Explanation:

1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

The above arrows point to positions where the corresponding bits are different.

S: bit manipulation

    int hammingDistance(int x, int y) {
        int n = x ^ y;
        int count = 0;
        while (n) {
            count++;
            n &= n - 1;  //clear right most bits
        }
        return count;
    }

477. Total Hamming Distance

TheHamming distancebetween 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.

Example:

Input:
 4, 14, 2

Output:
 6

Explanation:
 In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
showing 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.

Note:
Elements of the given array are in the range of 0 to 10^9

Length of the array will not exceed 10^4.

S1:naive approach O(n^2)

    int totalHammingDistance(vector<int>& nums) {
        int n = 0, count = 0;
        for (int i = 0; i < nums.size(); ++i) {
            for (int j = i + 1; i < nums.size(); ++j) {
                n += nums[i] ^ nums[j];
            }
        }
        return n;
        while (n) {
            count++;
            n &= n - 1;
        }
        return count;
    }

S2: bit manipulation, 组合 O(n)

对所有数字的第k位,假设有m个数字第k位为0,n个数字第k位为1,取两个数的hamming distance只有当一个数在m中一个数在n中时,其hamming distance为1,这种组合有m*n种

    int totalHammingDistance(vector<int>& nums) {
        int result = 0, n = nums.size();
        for (int i = 0; i < 32; ++i) {
            int oneCount = 0;
            for (int j = 0; j < nums.size(); ++j) {
                oneCount += (nums[j] >> i) & 1;
            }
            result += oneCount * (n - oneCount);
        }
        return result;
    }

results matching ""

    No results matching ""