子网掩码+ip地址
Problem statement: C++ Program to find unique number in an array of n numbers in which except one (unique number) rest all are present thrice.
问题陈述: C ++程序在n个数字的数组中查找唯一数字,其中除一个(唯一数字)外其余所有其余三次。
Constraints: n<10^5
约束: n <10 ^ 5
Example:
例:
Input:
10
1 2 3 2 4 1 2 3 1 3
Output:
4
Solution: Except 4 rest all have multiplicity of 3 in array. For instance 4 are represented as 100 in binary .Starting from left most bit is the first index of count array.
解决方案:除了4个其余的所有数组都具有3的多重性。 例如,4用二进制表示为100.从最左边的位开始是count数组的第一个索引。
Problem explanation:
问题说明:
Make a count array (initialize all elements to 0) to store the bits of each number in input array.
创建一个计数数组(将所有元素初始化为0),以将每个数字的位存储在输入数组中。
In each iteration access the input number and extract its bits to store in count array for instance if number is 6 which is 110 in binary, so 110 & 1 stores 0 at count[0], then right shift the number to obtain the next bit from left that is 11 & 1 stores 1 at count[1] and similarly again >> number to get 1 again at count[2].
在每次迭代中,访问输入数字并提取其比特以存储在计数数组中,例如,如果数字为6(二进制数为110),则110&1在count [0]处存储0,然后右移数字以获得下一个比特从11&1的左起在count [1]处存储1,同样>> >>在count [2]处再次获得1。
After each iteration count array is updated. Now since every element except one occurs thrice in input array, therefore bits at every index exist in the form of 3n and 3n +1.
每次迭代后,更新计数数组。 现在,由于除一个元素外的每个元素都在输入数组中出现三次,因此每个索引处的位都以3n和3n +1的形式存在。
So taking modulus by 3 leaves only unique number's bits in count array as remainders. This will give the binary number of the unique number.
因此,将模数减3只会在计数数组中保留唯一数字的位数作为余数。 这将给出唯一编号的二进制编号。
Now convert binary to decimal by ∑ multiply (bit with 2^index at respective index).
现在,将∑乘以将二进制转换为十进制(在相应的索引处具有2 ^ index的位)。
Return the unique number in array.
返回数组中的唯一编号。
Program:
程序:
#include <iostream>
using namespace std;
int unique(int *arr,int n)
{
//array of size 64 for max 64 bit size
int count[64]={0};
//count array stores bit of every number
for(int k=0;k<n;k++)
{
int i=0;
int num=arr[k];
while(num>0)
{
// extract bit
count[i]+=(num&1);
i++;
// right shift to get next leftmost bit
num=num>>1;
}
}
// starting from first index 2^0=1
int power=1;
int result=0;
for(int j=0;j<64;j++)
{
// take modulus of count array by 3
count[j] %=3;
result+=count[j]*power;
// binary to decimal operation
power=power<<1;
}
// if there is no unique number 0 is returned
return result;
}
int main()
{
int arr[50];
int n;
cout<<"Enter lenght of the array: ";
cin>>n;
cout<<"Enter array elements..."<<endl;
for(int c=0;c<n;c++)
{
cin>>arr[c];
}
cout<<unique(arr,n)<<" is the unique number in array.";
return 0;
}
Output
输出量
Enter lenght of the array: 4
Enter array elements...
10 10 10 40
40 is the unique number in array.
翻译自: https://www.includehelp.com/cpp-programs/find-unique-number-using-bit-masking.aspx
子网掩码+ip地址