Loading... ## 例题一: 给出一个数组,只有一个数字出现次数为奇数次,其余数字出现都为偶数次,找出那一个数字: ### 实现思路: 我们可以遍历数组,全部异或一遍,最后的结果即为那个数字! ### 代码实现: ```cpp #include<iostream> #include<algorithm> using namespace std; int main(){ int a[] = {1, 1, 2, 2, 3}; int eor = 0; for(int i = 0; i < 5; i++){ eor ^= a[i]; } cout<<eor; return 0; } ``` ## 例题二: 同样是给出一个数组,有两个数字出现次数为奇数次,其余数字出现都为偶数次,找出那两个数字 ### 代码实现: ```cpp #include<iostream> #include<algorithm> using namespace std; int main(){ int a[] = {1, 1, 2, 2, 3, 4}; int eor = 0; for(int i = 0; i < 6; i++){ eor ^= a[i]; } int rightOne = eor & (~eor + 1); //取出最右的1 int onlyOne = 0; for(int i = 0; i < 6; i++){ if((a[i] & rightOne) == 1){ onlyOne ^= a[i]; } } eor^=onlyOne; cout<<onlyOne<<" "<<eor; return 0; } ``` 最后修改:2022 年 01 月 20 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果文章有用,请随意打赏。