477. Total Hamming Distance

来源:互联网 发布:淘宝代理加盟的骗局 编辑:程序博客网 时间:2024/06/07 03:13

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.

Example:

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.

Note:

  1. Elements of the given array are in the range of to 10^9
  2. Length of the array will not exceed 10^4.

Subscribe to see which companies asked this question.

进化过程:

public class _477 {public int totalHammingDistance(int[] nums) {int[] zero = new int[32];int[] one = new int[32];int len = nums.length;for (int i = 0; i < 32; ++i)zero[i] = len;for (int n : nums) {int i = 0;while (n != 0) {int cur = n % 2;n /= 2;if (cur == 1) {zero[i] -= 1;one[i] += 1;}i += 1;}}int re = 0;for (int i = 0; i < 32; ++i)re += zero[i] * one[i];return re;}}

public class _477plus {public int totalHammingDistance(int[] nums) {int[] one = new int[32];int len = nums.length;for (int n : nums) {int i = 0;while (n != 0) {if (n % 2 == 1)one[i] += 1;i += 1;n /= 2;}}int re = 0;for (int i = 0; i < 32; ++i)re = re + one[i] * (len - one[i]);return re;}}

public class _477plusplus {public int totalHammingDistance(int[] nums) {int len = nums.length;int re = 0;for (int i = 0; i < 32; ++i) {int one = 0;for (int n : nums)one += (n >> i) & 1;re += one * (len - one);}return re;}}