在C语言中,XOR是如何找到奇数次出现的数的? int getOddOccurrence(int ar[],int ar_size){ int i; int res=0; 对于(i=0;i
与上面的代码一样,xor如何获得数组中奇数的出现次数?它没有在C语言中,XOR是如何找到奇数次出现的数的? int getOddOccurrence(int ar[],int ar_size){ int i; int res=0; 对于(i=0;i,c,C,与上面的代码一样,xor如何获得数组中奇数的出现次数?它没有res+=ar[i]&1;然而,这并不重要 Xor不生成进位,因此其计数不能超过1位: int getOddOccurrence(int ar[], int ar_size) { int i; int res = 0; for (i=0; i < ar_size; i++) res = res ^ ar[i]; return res; } /* Diver function to t
res+=ar[i]&1
;然而,这并不重要
Xor不生成进位,因此其计数不能超过1位:
int getOddOccurrence(int ar[], int ar_size) {
int i;
int res = 0;
for (i=0; i < ar_size; i++)
res = res ^ ar[i];
return res;
}
/* Diver function to test above function */
int main() {
int ar[] = {2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2};
int n = sizeof(ar)/sizeof(ar[0]);
printf("%d", getOddOccurrence(ar, n));
return 0;
}
但是,它会产生线性奇偶校验(在相同位置的所有位之间的奇偶校验(即所有位7、所有位6的奇偶校验)。如果具有相同位索引的ar
中的所有位之和为奇数,则res中任何位的结果为1
它与每个字节的奇偶校验相结合,形成一个矩阵,在这个矩阵中,可以检测并纠正一个位错误,而可以检测(但未纠正)一个两位错误
这在早期被用作某些传输协议的(弱)前向纠错。如今,有更好但处理更密集的算法,如汉明码
编辑:
其他评论和答案表明,这是为了找到外观奇特的单一值。由于这对输入造成了相当多的限制,因此它没有实际用途,纯粹是人为的。然而,上述应用程序明确是真实的(或已经存在).此代码不计算奇数的出现次数。相反,它在数组中查找出现奇数次的单个数字 您的测试阵列具有以下数字:
I1 I2 I1^I2
0 0 0
0 1 1
1 0 1
1 1 0
I1: bit[k] of res
I2: bit[k] of ar[i]
k = 0 ... (sizeof(int) * CHAR_BIT - 1) (number of bits in int - 1)
他们的人数如下:
2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2
只有5次被列为奇数次
XOR具有以下两个属性:
2 - 4 times
3 - 2 times
4 - 4 times
5 - 3 times
对于X和Y的任何值。换句话说,用零对任何数字
Y
进行异或运算会使值保持不变,用任何值Y
对数字X
进行两次异或运算会使原始值保持不变。运算顺序无关紧要。因为res
从零开始,所以将arr中的所有数字异或运算在一起ay产生5-唯一一个不是偶数次异或运算的值。嗨,这是我查找两个奇数的代码,这是我在大学里的实验室任务。希望你能理解这个概念
Y ^ 0 = Y
X ^ X ^ Y = Y
它不计算它们。它使用一种有效的“技巧”来识别列表中出现奇数的数字的单个实例。如果有多个或没有出现奇数次的数字,这种技巧将不起作用
如果将一个数字与其自身进行异或运算,则它等于0。此属性即使在多个运算中也适用,即3^4^3^4=0。因此,在这样的序列中,最终结果将等于任何不“取消”的数字。即3^4^3=4。将其写在纸上。制作一个小数组,手动执行
xor
,并观察位模式改变…我做到了,但实际上我想知道这是如何计算的?@bigBunny它不起作用。:)它不起作用。您的代码段是这样的。Xor表示位的奇偶校验,而不是数字。这是怎么做的?int i;int res=0;对于(i=0;i void printTwoOdd(int arr[], int size)
{
int xor2 = arr[0]; /* Will hold XOR of two odd occurring elements */
int set_bit_no; /* Will have only single set bit of xor2 */
int i;
int n = size - 2;
int x = 0, y = 0;
/* Get the xor of all elements in arr[]. The xor will basically
be xor of two odd occurring elements */
for(i = 1; i < size; i++)
xor2 = xor2 ^ arr[i];
/* Get one set bit in the xor2. We get rightmost set bit
in the following line as it is easy to get */
set_bit_no = xor2 & ~(xor2-1);
/* Now divide elements in two sets:
1) The elements having the corresponding bit as 1.
2) The elements having the corresponding bit as 0. */
for(i = 0; i < size; i++)
{
/* XOR of first set is finally going to hold one odd
occurring number x */
if(arr[i] & set_bit_no)
x = x ^ arr[i];
/* XOR of second set is finally going to hold the other
odd occurring number y */
else
y = y ^ arr[i];
}
printf("\n The two ODD elements are %d & %d ", x, y);
}
void main()
{
int arr[] = {4, 2, 4, 5, 2, 3, 3, 1};
int arr_size = sizeof(arr)/sizeof(arr[0]);
printTwoOdd(arr, arr_size);
getchar();
}