1.题目背景
2.知识基础
关于此类找只出现过一次的,基本上用异或解法就可以。
异或用来接出现过一次的题,可以算是标准答案
- 异或基础
异或运算也称为XOR,其运算法则相当于不带进位的二进制加法。如果a、b两个二进制位不相同,则异或结果为1。如果a、b两个二进制位相同,异或结果为0。同为0,异为1. 异或符号在c/c++中用^表示。
- 异或性质
(1) 0^a = a. 0与任何数进行异或运算结果等于该数。
(2) a^a = 0. 两个相同数进行异或运算结果等于0.
- 性质应用
举个题目中例子,
int ans = 0,
那么ans ^ 1 ^ 1 ^ 2 ^ 2 ^ 5 = 5
异或运算中出现相同的两个数计算结果为0(特性2),
剩下的那一个数与0进行异或运算结果等于该数(特性1)。
3.实现代码
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
//此外还有逗号分隔字符串的问题,比较简单
string line;
getline(cin, line);
int len = line.size();
for (int i = 0; i < len; i++)
{
if (line[i] == ',')
{
line[i] = ' ';
}
}
stringstream ss(line);
int temp;
int ans = 0;
while (ss >> temp)
{
ans = ans^temp;
}
cout << ans << endl;
}
4.扩展
- 一个数组各位均不同,只有一个数出现过两次
解法:
数组本身依次与其他位,数组异或运算,最终结果就是答案;——异或三次的数会保留下来
PS.复杂度太高;还是改用双指针或者Set
//伪代码
ans=0;
base = vector[0];
while(1){
for( i = vector.begin();i!=vector.end;i++)
{
ans = base^(*i);
}
base = next vector;
if(base == vector.back())
break;
}