HDU-2095-find your present (2)-位或/STL(set)
In the new year party, everybody will get a "special present".Now it's your turn to get your special present, a lot of presents now putting on the desk, and only one of them will be yours.Each present has a card number on it, and your present's card number will be the one that different from all the others, and you can assume that only one number appear odd times.For example, there are 5 present, and their card numbers are 1, 2, 3, 2, 1.so your present will be the one with the card number of 3, because 3 is the number that different from all the others.
InputThe input file will consist of several cases.
Each case will be presented by an integer n (1<=n<1000000, and n is odd) at first. Following that, n positive integers will be given in a line, all integers will smaller than 2^31. These numbers indicate the card numbers of the presents.n = 0 ends the input.OutputFor each case, output an integer in a line, which is the card number of your present.Sample Input
5
1 1 3 2 2
3
1 2 1
0
Sample Output
3
2
use scanf to avoid Time Limit Exceeded
Hint
Hint
题意:
给出n,说明有n个数字,要求找出一个与其他数字不同的那个数,只有需要找的那个数字出现过奇数次,其他都是偶数次。
法一:
这是用容器写的,用了set
s.find(x)!=s.end() 说明找到了
s.erase(x); 找到和它一样的就把它删掉
s.insert(x); 没有找到就把这个数字插入
需要注意的是:题目说了,找到的那个数字是奇数个,而其他数字都是偶数个,所以可以利用set,否则要是我们需要找3,给出一组数据2、2、2、3像这样是找不出来的。

1 #include<iostream> 2 #include<iomanip> 3 #include<string.h> 4 #include<set> 5 #define inf 0x3f3f3f3f 6 using namespace std; 7 8 int main() 9 { 10 std::ios::sync_with_stdio(false); 11 cin.tie(0); 12 cout.tie(0); 13 int n; 14 while(cin>>n) 15 { 16 if(n==0) 17 break; 18 set<int>s; 19 s.clear(); 20 int x; 21 for(int i=0;i<n;i++) 22 { 23 cin>>x; 24 if(s.find(x)!=s.end())//找到了 25 s.erase(x);//删掉 26 else//没有找到 27 s.insert(x); 28 } 29 cout<<*s.begin()<<endl; 30 } 31 return 0; 32 }
法二:
利用位运算

1 #include<iostream> 2 #include<iomanip> 3 #include<string.h> 4 #include<set> 5 #define inf 0x3f3f3f3f 6 using namespace std; 7 8 int main() 9 { 10 std::ios::sync_with_stdio(false); 11 cin.tie(0); 12 cout.tie(0); 13 int n; 14 while(cin>>n) 15 { 16 if(n==0) 17 break; 18 int x=0;//0和任何非0数m异或都为0; 19 for(int i=0;i<n;i++) 20 { 21 int ss; 22 cin>>ss; 23 x=x^ss; 24 } 25 cout<<x<<endl; 26 } 27 return 0; 28 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」