10.2Single Number位运算基础问题
题目描述
给定一个整数数组,这个数组里只有一个数字出现了一次,其余数字出现了两次,求这个只出现一次的数字。
输入输出样例
Input :[4, 1, 2, 1, 2]
Output:4
输入一个一维整数数组,输出是该数组内的一个整数
题解
我们可以利用x^x = 0 和x ^ 0 = x 的特点,将数组内所有的数字进行按位异或。出现两次的所有数字按位异或的结果是0,0与出现一次的数字亦或可以得到这个数字本身。
cpp
#include <iostream>
#include <vector>
using namespace std;
int sigleNumber(vector<int>& nums) {
int ans = 0;
for (const int& num : nums) {
ans = ans ^ num;
}
return ans;
}
int main() {
vector<int> ans = { 4,1,2,1,2 };
cout << sigleNumber(ans) << endl;
return 0;
}