描述
给出N个数字。其中仅有一个数字出现过一次,其他数字均出现过两次,找出这个出现且只出现过一次的数字。要求时间和空间复杂度最小。
输入
输入多个数字,每个数字以空格分开。数字数量 N < 20,输入数字的最大值小于 256.
输出
输出内容为只出现过唯一一次的数字
输入样例
10 10 11 12 12 11 16
输出样例
16
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <ctype.h>
int main()
{
// please write your code here
int a[20],b=0,i,m;
char s;
for(i=0;i<20&&s!='\n';i++)
{
scanf("%d",&a[i]);
s=getchar();
}
for(m=0;m<i;m++)
{
b=b^a[m];
}
printf("%d\n",b);
}
心得:
- c语言中^表示异或
- a,b为0或1,a=b时 a^b=0;a≠b时 a^b=1
- 任何数与0异或都是这个数本身
- 本次题目中,输入的数字连续异或,即a^b ^c ^d… 结果就是单独出现的数字