求两个整数之间的汉明距离-salem

Salem is known to be one of the best competitive programmers in the region. However, he always finds a hard time understanding the concept of the hamming distance. The hamming distance of two numbers is defined as the number of different digits in their binary representations (leading zeros are used if necessary to make the binary representations have the same length). For example the hamming distance between 12 and 5 is 2 since their binary representations are 1100 and 0101 respectively and they differ in the first and fourth positions.

Recently, Salem got a problem that he needs your help to solve. He is given N integers and asked to get the maximum among the hamming distances of all possible pairs of the given integers.

Input

The first line of the input will be a single integer T representing the number of test cases. Followed by T test cases. Each test case will start with a line with single integer (2 ≤ N ≤ 100) representing the number of the integers. Each of the following N lines contains one of the integers (1 ≤ Ai ≤ 10, 000) from the list of the integers.

Output

For each test case print one line consists of one integer representing the maximum hamming distance between all possible pairs from the given integers.

Example
Input

2
2
12
5
3
1
2
3

Output

2
2

题目大意:
给你任意个整数,然后求出这些整数中汉明距离最大的一对数并输出距离。

解题思路:
所谓汉明距离就是给定两个相同长度的字符串,找出字符串中相同位置不同值的元素个数。
在这个题目中使用到二进制的异或运算,因为异或的规则是两个数相同为0,不同为1,所以只需将两个数进行异或运算再求出其结果整数的二进制数中1的个数即可。
而计算

一个二进制中1的个数可以使用:
计算机里的数字本来就是用二进制存的,所以计算过程也都是二进制计算。利用一些位运算的特性,可以很容易计算1的个数。

有一个很有意思的特性:随便给一个二进制数,比如n=10001100,我们把它减一:n-1=10001011。重新摆放一下观察:
10001100 (n)
10001011 (n-1)
通过观察得出,n中为1的最低位是第3位,而n-1和n的低3位全都不同。如果进行“按位与”操作,即 n & (n-1) = 10001000。
10001100 (n)
10001011 (n-1)
10001000 (n & (n-1))
可以看到底3位都变成了0。
如果你数学足够好,可以得出结论:

[结论]要消除整数n最低位的1,可以使用 n = n & (n-1)。

所以代码为:

int check(int n)
{
    int c=0;
    while(n)
    {
        n=n&(n-1);
        c++;
    }
    return c;
}

此题代码为:

#include
#include
using namespace std;
int check(int n)
{
    int c=0;
    while(n)
    {
        n=n&(n-1);
        c++;
    }
    return c;
}
int main()
{
    int n;
    int a[105];
    cin>>n;
    while(n--)
    {
        int n1;
        cin>>n1;
        int maxx=0;
        for(int i=1;i<=n1;i++)
        {
            cin>>a[i];
        }
        for(int i=1;i<=n1;i++)
        {
            for(int j=i+1;j<=n1;j++)
            {
                int m=check(a[i]^a[j]);
//                cout<<"m: "<
                if(m>maxx)
                    maxx=m;
            }
        }
        cout<

你可能感兴趣的:(二进制,数学)