LeetCode——Hamming Distance

来源:互联网 发布:成都租房 知乎 编辑:程序博客网 时间:2024/06/06 06:47

461 Hamming Distance

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

Given two integers x and y, calculate the Hamming distance.
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.

public class Solution {public int hammingDistance(int x, int y) {    int cnt = 0;    int ans = x ^ y;    while(ans > 0){        if(ans%2==1)        {            cnt+=1;        }        ans/=2;    }    return cnt;}

}

477 Total Hamming Distance

Total Accepted: 14132
Total Submissions: 30521
Difficulty: Medium
Contributors:
kevin.xinzhao@gmail.com
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, 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.

public class Solution {public int totalHammingDistance(int[] nums) {    int n = 31;    int len = nums.length;    int[] countOfOnes = new int[n];    for (int i = 0; i < len; i++)//对待每一个数字    {        for (int j = 0; j < n; j++)//每一位数字        {            countOfOnes[j] += (nums[i] >> j) & 1;//统计这一个位置是0还是1        }    }    int sum = 0;    for (int count: countOfOnes) {        sum += count * (len - count);    }    return sum;}

}

解释一下他大概的原理:

如果从每两个数字去组合考虑那么会LTE,所以从所有数字的某一个位置考虑,假设这个数组上所有数字的某一个位置上已知有x个1,y个0,那么这个位置上最终各种各样全部异或一遍加起来应该就是 x*y个1(因为x^x = y^y =0),即,你在这个位置所有数字有x个1,y个0,异或之后留下来就会有x*y个1;

感想

脑子是个好东西