按位异或运算符“^”是双目运算符。
其功能是参与运算的两数各对应的二进位相异或,当两对应的二进位相异时,结果为1,当两对应的二进位相同时,结果为0。
而计算机中存储的是以补码形式的二进制数,我们又知道一个数和自身异或为0,所以代码如下:
注意:
代码有缺陷:无法求两个或两个以上单独的数!
#define _CRT_SECURE_NO_WARNINGS 0 #include <stdio.h> int main() { int i = 0; int arr[] = {2,2,1,3,8,5,4,5,6,7,1,4,7,9,8,6,9}; int res = arr[0]; int sz = sizeof(arr)/sizeof(arr[0]); for(i=1;i<sz;i++) { res ^= arr[i]; } printf("%d\n",res); return 0; }