计蒜客————单独的数字

来源:互联网 发布:mac电脑excel内存不足 编辑:程序博客网 时间:2024/06/08 00:37
  •  28.46%
  •  1000ms
  •  65536K

给定一个数组 AA,除了一个数出现一次之外,其余数都出现三次。找出出现一次的数。

如:\{1, 2, 1, 2, 1, 2, 7\}{1,2,1,2,1,2,7},找出 77

你的算法只能是线性时间的复杂度,并且不能使用额外的空间哦~

输入格式

第一行输入一个数 n(1 \leq n \leq 500)n(1n500),代表数组的长度。

接下来一行输入 nn 个 int 范围内(-2147483648\ldots 214748364721474836482147483647)的整数,表示数组 AA。保证输入的数组合法。

输出格式

输出一个整数,表示数组中只出现一次的数。

样例输入

40 0 0 5

样例输出

5
int 二进制下共32位,每出现3个数,统计可得32位出现次数余3为0,若只出现一次,其出现次数余3为1,所以通过统计 各个 位数出现次数,判断多出来什么数。。
#include<iostream>#include<stdio.h>#include<stdlib.h>#include<math.h>using namespace std;int main(){    int N;    while(cin>>N)    {        int  com[32]= {};        while(N--)        {            int temp;            cin>>temp;            for(int i=0; i<32; i++)                com[i]+=((temp>>i)&1);        }        int pow2=1,ans=0;        for(int i=0; i<32; i++)        {            ans+=pow2*(com[i]%3);            pow2*=2;        }        cout<<ans<<endl;    }    return 0;}
原创粉丝点击